Kmeans是需要指定类别的不需要监督的学习
# 加载数据 import pandas as pd import numpy as np from matplotlib import pyplot as plt from sklearn.cluster import KMeans from sklearn.metrics import accuracy_score if __name__ == '__main__': data = pd.read_csv('data/data2.csv') data.head() # define X and y X = data.drop(['labels'], axis=1) # axis意思是按照列 y = data.loc[:, 'labels'] # :->所有行 ‘labels’这一列 pd.value_counts(y) # 这是察看这一列所有的值和出现次数 fig1 = plt.figure() label0 = plt.scatter(X.loc[:,'V1'][y==0],X.loc[:,'V2'][y==0]) label1 = plt.scatter(X.loc[:,'V1'][y==1],X.loc[:,'V2'][y==1]) label2 = plt.scatter(X.loc[:,'V1'][y==2],X.loc[:,'V2'][y==2]) plt.title('un-labled data') plt.xlabel('V1') plt.ylabel('V2') plt.legend((label0,label1,label2),('label0','label1,','label2')) plt.show() # 创建模型 KM = KMeans(n_clusters=3, random_state=0) KM.fit(X) # 得到中心点 和原来的图像放在一起观看 centers = KM.cluster_centers_ fig3 = plt.figure() label0 = plt.scatter(X.loc[:, 'V1'][y == 0], X.loc[:, 'V2'][y == 0]) label1 = plt.scatter(X.loc[:, 'V1'][y == 1], X.loc[:, 'V2'][y == 1]) label2 = plt.scatter(X.loc[:, 'V1'][y == 2], X.loc[:, 'V2'][y == 2]) plt.title('un-labled data') plt.xlabel('V1') plt.ylabel('V2') plt.scatter(centers[:,0],centers[:,1]) plt.legend((label0, label1, label2), ('label0', 'label1,', 'label2')) plt.show() # 预测结果 KM.predict([[80,60]]) # 发现结果对但是标识顺序乱了 y_predict = KM.predict(X) print(pd.value_counts(y_predict),pd.value_counts(y)) #计算准确率 你会发现低的可怜 这是因为你的标识和颜色没有对上,需要修改 accuracy = accuracy_score(y,y_predict) fig4 = plt.subplot(121) label0 = plt.scatter(X.loc[:, 'V1'][y_predict == 0], X.loc[:, 'V2'][y_predict == 0]) label1 = plt.scatter(X.loc[:, 'V1'][y_predict == 1], X.loc[:, 'V2'][y_predict == 1]) label2 = plt.scatter(X.loc[:, 'V1'][y_predict == 2], X.loc[:, 'V2'][y_predict == 2]) plt.title('predict data') plt.xlabel('V1') plt.ylabel('V2') plt.legend((label0, label1, label2), ('label0', 'label1,', 'label2')) plt.scatter(centers[:,0],centers[:,1]) fig5 = plt.subplot(122) label0 = plt.scatter(X.loc[:, 'V1'][y == 0], X.loc[:, 'V2'][y == 0]) label1 = plt.scatter(X.loc[:, 'V1'][y == 1], X.loc[:, 'V2'][y == 1]) label2 = plt.scatter(X.loc[:, 'V1'][y == 2], X.loc[:, 'V2'][y == 2]) plt.title('un-labled data') plt.xlabel('V1') plt.ylabel('V2') plt.legend((label0, label1, label2), ('label0', 'label1,', 'label2')) plt.scatter(centers[:, 0], centers[:, 1]) plt.show() # 无监督的学习 是没有标识的 需要修改 y_corrected = [] for i in y_predict: if i==0: y_corrected.append(1) elif i == 1: y_corrected.append(2) else: y_corrected.append(0)