from sklearn.cluster import KMeans
import numpy as np
import matplotlib.pyplot as plt
data = np.genfromtxt("kmeans.txt", delimiter=" ")
k = 4
model = KMeans(n_clusters=k)
model.fit(data)
![sklearn实现k-means算法_第1张图片](http://img.e-com-net.com/image/info8/ba9353b61a794128bdd7c786264d879a.png)
centers = model.cluster_centers_
print(centers)
![sklearn实现k-means算法_第2张图片](http://img.e-com-net.com/image/info8/39f73630908f4280913a993352ef0bc0.png)
result = model.predict(data)
print(result)
![sklearn实现k-means算法_第3张图片](http://img.e-com-net.com/image/info8/50e4ef1dc28a4a8887f6f719828d9eaf.png)
model.labels_
![sklearn实现k-means算法_第4张图片](http://img.e-com-net.com/image/info8/9aa3afe49961486ea4f90e6217fa0b98.png)
mark = ['or', 'ob', 'og', 'oy']
for i,d in enumerate(data):
plt.plot(d[0], d[1], mark[result[i]])
mark = ['*r', '*b', '*g', '*y']
for i,center in enumerate(centers):
plt.plot(center[0],center[1], mark[i], markersize=20)
plt.show()
![sklearn实现k-means算法_第5张图片](http://img.e-com-net.com/image/info8/b9e3e1848bb547cd88699e504f7fee29.png)
x_min, x_max = data[:, 0].min() - 1, data[:, 0].max() + 1
y_min, y_max = data[:, 1].min() - 1, data[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
np.arange(y_min, y_max, 0.02))
z = model.predict(np.c_[xx.ravel(), yy.ravel()])
z = z.reshape(xx.shape)
cs = plt.contourf(xx, yy, z)
mark = ['or', 'ob', 'og', 'oy']
for i,d in enumerate(data):
plt.plot(d[0], d[1], mark[result[i]])
mark = ['*r', '*b', '*g', '*y']
for i,center in enumerate(centers):
plt.plot(center[0],center[1], mark[i], markersize=20)
plt.show()
![sklearn实现k-means算法_第6张图片](http://img.e-com-net.com/image/info8/9447706d39d4462a94124974113b728d.jpg)