from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt # 可视化数据
# 生成数据
n_samples = 200
n_clusters = 3
random_state = 42
X, y = make_blobs(n_samples=n_samples, centers=n_clusters, random_state=random_state)
# 使用KMeans算法
kmeans = KMeans(n_clusters=n_clusters, random_state=random_state)
kmeans.fit(X)
# 输出聚类结果
print("Cluster labels:", kmeans.labels_)
print("Cluster centers:", kmeans.cluster_centers_)
plt.scatter(X[:, 0], X[:, 1], c=y, cmap='viridis', label='Points')
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], c='red', marker='x', label='Centers')
plt.xlabel('X1')
plt.ylabel('X2')
plt.legend()
plt.show()
![](https://img2024.cnblogs.com/blog/1351803/202401/1351803-20240104140811625-1925575691.png)