【发布时间】:2022-01-23 01:35:12
【问题描述】:
当我使用此代码在 2D 中绘制聚类结果时:
from matplotlib import pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
# create 2d data
x, label = make_blobs(n_samples=3000, n_features=2, centers=4,
cluster_std=3, random_state=42)
# cluster data
kmeans = KMeans(init="k-means++", n_clusters=4, random_state=42)
kmeans.fit(x)
# plot clusters and centroids
fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111)
ax.scatter(x[:,0],x[:,1], c=kmeans.labels_, cmap='viridis',
edgecolor='k', s=40, alpha = 0.5)
ax.scatter(kmeans.cluster_centers_[:,0], kmeans.cluster_centers_[:,1],
s = 300, c = 'r', marker='*', label = 'Centroid')
ax.set_title("2D Kmeans clustering")
ax.set_xlabel("X")
ax.set_ylabel("Y")
plt.show()
我得到以下输出:
但是当我尝试使用此代码在 3D 中绘制聚类结果时:
from matplotlib import pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
# create 3d data
x, label = make_blobs(n_samples=3000, n_features=3, centers=4,
cluster_std=3, random_state=42)
# cluster data
kmeans = KMeans(init="k-means++", n_clusters=4, random_state=42)
kmeans.fit(x)
# plot clusters and centroids
fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x[:,0], x[:,1], x[:,2] ,c=kmeans.labels_, cmap='viridis',
edgecolor='k', s=40, alpha = 0.5)
ax.scatter(kmeans.cluster_centers_[:,0], kmeans.cluster_centers_[:,1],
kmeans.cluster_centers_[:,2], s = 300, c = 'r',
marker='*', label = 'Centroid')
ax.set_title("3D Kmeans clustering")
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
plt.show()
我得到以下输出:
如您所见,每个集群的质心不可见。我想在 3d 图中看到质心星星,我该如何实现?
提前感谢您的帮助!
【问题讨论】:
标签: python matplotlib scikit-learn k-means