基於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) # 顯示預測準確率
運行結果: