\编译器:pycharm
1.导入K-means相关包
这个包导入有点坑,有许多依赖包需要导入,推荐下载Anaconda后,在pycharm导入Anaconda中的python,在下载sklearn包,就可以开心的敲代码了~!
2正式开始:
from sklearn.cluster import KMeans
from sklearn.externals import joblib
from sklearn import cluster
import numpy as np
import matplotlib.pyplot as plt
data = np.random.rand(100,2) #生成长度为100,宽度为2的数据集,服从“0~1”均匀分布的随机样本值
estimator=KMeans(n_clusters=3)
print(data)
res=estimator.fit_predict(data) #返回 labels_
# 预测类别标签结果
lable_pred=estimator.labels_
# 各个类别的聚类中心值
centroids=estimator.cluster_centers_
# 聚类中心均值向量的总和
inertia=estimator.inertia_
print ('res',res)
print ('lable_pred:',lable_pred)
print ('centroids:',centroids)
print ('inertia:',inertia)
#对每一类的数据在坐标系上展示并规定颜色
for i in range(len(data)):
if int(lable_pred[i])==0:
plt.scatter(data[i][0],data[i][1],color='red')
if int(lable_pred[i])==1:
plt.scatter(data[i][0],data[i][1],color='black')
if int(lable_pred[i])==2:
plt.scatter(data[i][0],data[i][1],color='blue')
plt.show()
本案例是随机生成的二维数组