• 第八次作业


    import numpy as np
    x = np.random.randint(1,50,[20,1])
    y = np.zeros(20)
    k = 3
    
    def initcenter(x, k): kc
    def initcenter(x,k):
        return x[:k]
     
    kc = initcenter(x,k)
    kc
    
    def nearest(kc,i):
        d=(abs(kc-i))
        w=np.where(d==np.min(d))
        return w[0][0]
     
    kc = initcenter(x,k)
    def nearest(kc,i):
        d=(abs(kc-i))
        w=np.where(d==np.min(d))
        return w[0][0]
     
    kc = initcenter(x,k)
    nearest(kc,93)
    def xclassify(x,y,kc):
        for i in range(x.shape[0]):
            y[i] = nearest(kc,x[i])
        return y
     
    kc = initcenter(x,k)
    y = xclassify(x,y,kc)
    print(kc,y)
    
    def kcmean(x,y,kc,k):
        l = list(kc)
        flag = False
        for c in range(k):
            m = np.where(y == c)
            n = np.mean(x[m])
            if l[c] != n:
                l[c] = n
                flag = True
                print(l,flag)
        return (np.array(l),flag)
     
    kc = initcenter(x,k)
    flag = True
    k = 3
     
    
    while flag:
        y = xclassify(x,y,kc)
        kc,flag = kcmean(x,y,kc,k)  

    截图

    import numpy as np
    from sklearn.datasets import load_iris   
    iris = load_iris()
    x = iris.data[:,2]
    y = np.zeros(150)
     
    def initcenter(x,k):    #初始聚类中心数组
        return x[:k]
     
    def nearest(kc,i):       #数组中的值,与聚类中心最小距离所在类别的索引号
        d = (abs(kc-i))
        w = np.where(d == np.min(d))
        return w[0][0]
     
    def xclassify(x,y,kc):
        for i in range(x.shape[0]):       #对数组的每个值进行分类,shape[0]读取矩阵第一维度的长度
            y[i] = nearest(kc,x[i])
        return y
     
    def kcmean(x,y,kc,k):     #计算各聚类新均值
        l = list(kc)
        flag = False
        for c in range(k):
            print(c)
            m = np.where(y == c)
            if len(m) == 1:
                n = x[c]
            else:
                n=np.mean(x[m])
            if l[c] != n:
                l[c] = n
                flag = True     #聚类中心发生变化
                print(l,flag)
        return (np.array(l),flag)
     
     
    k = 3
    kc = initcenter(x,k)
     
    flag = True
    print(x,y,kc,flag)
     
    #判断聚类中心和目标函数的值是否发生改变,若不变,则输出结果,若改变,则返回2
    while flag:
        y = xclassify(x,y,kc)
        kc, flag = kcmean(x,y,kc,k)
        print(y,kc,type(kc))
         
    print(x,y)
    import matplotlib.pyplot as plt
    plt.scatter(x,x,c=y,s=50,cmap="Paired");
    plt.show()

  • 相关阅读:
    CF446DDZY Loves Games【高斯消元,矩阵乘法】
    PHP操作MongoDB数据库
    PHP linux spl_autoload_register区分大小写
    win7 64位安装redis 及Redis Desktop Manager使用
    svn的搭建
    php 扩展 redis
    CI reids 缓存
    拿起键盘写下我的第一封博客
    自我介绍
    课程目标
  • 原文地址:https://www.cnblogs.com/dalin-lyl/p/9886124.html
Copyright © 2020-2023  润新知