k均值聚类算法原理详解
示例为链接中的例题
直接调用python机器学习的库scikit-learn中k均值算法的相关方法
from sklearn.cluster import KMeans
import numpy as np
import matplotlib.pyplot as plt
x = np.array([[0,2],[0,0],[1,0],[5,0],[5,2]])
#计算k均值聚类
kmeans = KMeans(n_clusters=2, random_state=0).fit(x)
#簇中心坐标
center = kmeans.cluster_centers_
#每一点的标签
kmeans_lab = kmeans.labels_
plt.scatter(x[:,0],x[:,1])
plt.show()
plt.scatter(x[:,0],x[:,1],c=kmeans_lab)
plt.scatter(center[:,0],center[:,1],c='blue',s=200,alpha=0.5)
plt.show()
运行结果