基於 K-Means 對 IRIS 資料集分類
阿新 • • 發佈:2019-01-06
基於sklearn 對 IRIS 資料集分類
關於聚類
聚類(Clustering)是一種無監督學習(unsupervised learning),簡單地說就是把相似的物件歸到同一簇中。簇內的物件越相似,聚類的效果越好。
關於 K-Means
K-Means演算法是最為經典的基於劃分的聚簇方法,是十大經典資料探勘演算法之一。簡單的說K-Means就是在沒有任何監督訊號的情況下將資料分為K份的一種方法。聚類演算法就是無監督學習中最常見的一種,給定一組資料,需要聚類演算法去挖掘資料中的隱含資訊。聚類演算法的應用很廣:顧客行為聚類,google新聞聚類等。
具體的演算法步驟如下:
- 隨機選擇K箇中心點
- 把每個資料點分配到離它最近的中心點;
- 重新計算每類中的點到該類中心點距離的平均值
- 分配每個資料到它最近的中心點;
- 重複步驟3和4,直到所有的觀測值不再被分配或是達到最大的迭代次數(R把10次作為預設迭代次數)。
sklearn 實現
from sklearn import datasets
from sklearn.cluster import KMeans
import numpy as np
def mode(a):
```求眾數子函式```
counts = np.bincount(a)
return np.argmax(counts)
def calc_acc(y_p, y):
```計算準確率子函式```
return sum(y_p==y)/y.shape[0]
if __name__ == '__main__':
iris = datasets.load_iris()
x = iris.get('data')
y = iris.get('target')
# 隨機劃分訓練集和測試集
num = x.shape[0] # 樣本總數
ratio = 7/3 # 劃分比例,訓練集數目:測試集數目
num_test = int(num/(1+ratio)) # 測試集樣本數目
num_train = num - num_test # 訓練集樣本數目
index = np.arange(num) # 產生樣本標號
np.random.shuffle(index) # 洗牌
x_test = x[index[:num_test],:] # 取出洗牌後前 num_test 作為測試集
y_test = y[index[:num_test]]
x_train = x[index[num_test:],:] # 剩餘作為訓練集
y_train = y[index[num_test:]]
kmeans = KMeans(n_clusters=3)
kmeans.fit(x_train)
centers = kmeans.cluster_centers_
for i in range(3):
index = y_train == i
p = kmeans.predict(x_train[index,:])
pp = mode(p) # 求實際類別為 i 所對應的類別標號 pp
kmeans.cluster_centers_[i] = centers[pp] # 相應的調整類別標號,以正確預測
y_test_pre = kmeans.predict(x_test)
print("y_test_pre:")
print(y_test_pre)
print("y_test:")
print(y_test)
# 計算分類準確率
acc = calc_acc(y_test_pre, y_test)
print('the accuracy is', acc) # 顯示預測準確率
執行結果: