10-2-Kmeans-demo.py 549 B

123456789101112131415161718192021222324
  1. import matplotlib.pyplot as plt
  2. from sklearn.cluster import KMeans
  3. from sklearn.datasets import make_blobs
  4. def show_kmeans():
  5. # 生成测试样本
  6. n_samples = 1500
  7. random_state = 170
  8. x, y = make_blobs(n_samples=n_samples, random_state=random_state)
  9. # 聚类,指定聚类个数为3
  10. y_pred = KMeans(n_clusters=3, random_state=random_state).fit_predict(x)
  11. # 画图
  12. plt.subplot(221)
  13. plt.scatter(x[:, 0], x[:, 1], c=y_pred)
  14. plt.title("K-means")
  15. plt.show()
  16. if __name__ == '__main__':
  17. show_kmeans()