import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans
data = np.array([[0, 0], [1, 2], [3, 1], [8, 8], [9, 10], [10, 7]])
k = 4
model = KMeans(n_clusters=k) model.fit(data)
centers = model.cluster_centers_
result = model.predict(data)
mark = ['or', 'og', 'ob', 'ok'] for i, d in enumerate(data): plt.plot(d[0], d[1], mark[result[i]])
mark = ['*r', '*g', '*b', '*k'] for i, center in enumerate(centers): plt.plot(center[0], center[1], mark[i], markersize=20)
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) plt.show()
|