第八次做業:聚類--K均值算法:自主實現與sklearn.cluster.KMeans調用


import
numpy as np x = np.random.randint(1,100,[20,1]) y = np.zeros(20) k = 3 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) nearest(kc,56) 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)

運行結果數組

 

二.鳶尾花花瓣長度數據作聚類並用散點圖顯示dom

import numpy as np
from sklearn.datasets import load_iris    
iris = load_iris()
x = iris.data[:,1]
y = np.zeros(150)

def initcenter(x,k):    #初始聚類中心數組
    return x[0:k].reshape(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)
        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="rainbow");
plt.show()

運行結果函數

 

相關文章
相關標籤/搜索