要求:html
1.用python實現K均值算法python
K-means是一個反覆迭代的過程,算法分爲四個步驟:算法
(x,k,y)dom
1) 選取數據空間中的K個對象做爲初始中心,每一個對象表明一個聚類中心;函數
def initcenter(x, k): kcspa
2) 對於樣本中的數據對象,根據它們與這些聚類中心的歐氏距離,按距離最近的準則將它們分到距離它們最近的聚類中心(最類似)所對應的類;rest
def nearest(kc, x[i]): jcode
def xclassify(x, y, kc):y[i]=jhtm
3) 更新聚類中心:將每一個類別中全部對象所對應的均值做爲該類別的聚類中心,計算目標函數的值;對象
def kcmean(x, y, kc, k):
4) 判斷聚類中心和目標函數的值是否發生改變,若不變,則輸出結果,若改變,則返回2)。
while flag:
y = xclassify(x, y, kc)
kc, flag = kcmean(x, y, kc, k)
2. 鳶尾花花瓣長度數據作聚類並用散點圖顯示。
3. 用sklearn.cluster.KMeans,鳶尾花花瓣長度數據作聚類並用散點圖顯示.
4. 鳶尾花完整數據作聚類並用散點圖顯示.
參考官方文檔: http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html#sklearn.cluster.KMeans
1.用python實現K均值算法 K-means是一個反覆迭代的過程,算法分爲四個步驟: import numpy as np x = np.random.randint(1,50,[20,1]) y = np.zeros(20) k = 3 #1) 選取數據空間中的K個對象做爲初始中心,每一個對象表明一個聚類中心; def initcenter(x,k): return x[:k] #2) 對於樣本中的數據對象,根據它們與這些聚類中心的歐氏距離,按距離最近的準則將它們分到距離它們最近的聚類中心(最類似)所對應的類; 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]): y[i] = nearest(kc, x[i]) return y kc = initcenter(x,k) y = xclassify(x,y,kc) print(kc,y) #3) 更新聚類中心:將每一個類別中全部對象所對應的均值做爲該類別的聚類中心,計算目標函數的值; def kcmean(x,y,kc,k): l = list(kc) flag = False for c in range(k): m = np.where(y ==0) n = np.mean(x[m]) if l[c] != n: l[c] = n flag = True print(l,flag) return (np.array(l),flag) #4) 判斷聚類中心和目標函數的值是否發生改變,若不變,則輸出結果,若改變,則返回2) kc = initcenter(x,k) flag = True print(x,y,kc,flag) while flag: y = xclassify(x,y,kc) kc,flag = kcmean(x,y,kc,k) print(y,kc)
運行結果:
2. 鳶尾花花瓣長度數據作聚類並用散點圖顯示。 from sklearn.datasets import load_iris iris = load_iris() datas = iris.data iris_length=datas[:,2] # 用鳶尾花花瓣做分析 x = np.array(iris_length) y = np.zeros(x.shape[0]) kc = initcen(x,3) flag = True while flag: y = xclassify(x,y,kc) kc,flag = kcmean(x,y,kc,3) print(kc,flag) # 分析鳶尾花花瓣長度的數據,並用散點圖表示出來 import matplotlib.pyplot as plt plt.scatter(iris_length, iris_length, marker='+', c=y, alpha=0.5, linewidths=4, cmap='Paired') plt.show()
運行結果:
3. 用sklearn.cluster.KMeans,鳶尾花花瓣長度數據作聚類並用散點圖顯示. from sklearn.cluster import KMeans iris_length = datas[:, 2:3] k_means = KMeans(n_clusters=3) result = k_means.fit(iris_length) kc1 = result.cluster_centers_ y_kmeans = k_means.predict(iris_length) #繪圖
plt.scatter(iris_length,np.linspace(1,150,150),c=y_kmeans,marker='*',cmap='rainbow',linewidths=4) plt.show()
4. 鳶尾花完整數據作聚類並用散點圖顯示. k_means1 = KMeans(n_clusters=3) result1 = k_means1.fit(datas) kc2 = result1.cluster_centers_ y_kmeans1 = k_means1.predict(datas) print(y_kmeans1, kc2) print(kc2.shape, y_kmeans1.shape, datas.shape) plt.scatter(datas[:, 0], datas[:, 1], c=y_kmeans1, marker='2', cmap='flag', linewidths=4, alpha=0.6) plt.show()
運行結果: