使用Kmeans的数据集的三维打印

2024-10-06 08:42:00 发布

您现在位置:Python中文网/ 问答频道 /正文

X, t = make_swiss_roll(n_samples=1000, noise=0.2, random_state=42)
from sklearn.cluster import KMeans

kmeans = KMeans(n_clusters=3)                   # Number of clusters == 3
kmeans = kmeans.fit(X)                          # Fitting the input data
labels = kmeans.predict(X)                      # Getting the cluster labels
centroids = kmeans.cluster_centers_             # Centroid values
print("Centroids are:", centroids)              # From sci-kit learn

fig = plt.figure(figsize=(20,10))
ax = fig.add_subplot(111, projection='3d')

x = np.array(labels==0)
y = np.array(labels==1)
z = np.array(labels==2)
ax.scatter(x,y,z, marker="s"[kmeans.labels_], s=40, cmap="RdBu")

我试图在3D中绘制集群,方法是为属于其类别的所有标签上色,并使用单独的符号绘制质心。我设法让KMeans技术发挥了作用,至少我相信我做到了。但我一直在尝试用3D绘制它。我相信会有一个简单的解决办法,我只是没看到而已。有人知道我需要在解决方案中改变什么来实现这一点吗


Tags: themakelabelsnpfig绘制axarray
2条回答

尝试此操作,现在群集为黑色X:

from sklearn.datasets import make_swiss_roll
X, t = make_swiss_roll(n_samples=1000, noise=0.2, random_state=42)
from sklearn.cluster import KMeans

kmeans = KMeans(n_clusters=3)                   # Number of clusters == 3
kmeans = kmeans.fit(X)                          # Fitting the input data
labels = kmeans.predict(X)                      # Getting the cluster labels
centroids = kmeans.cluster_centers_             # Centroid values
print("Centroids are:", centroids)              # From sci-kit learn

fig = plt.figure(figsize=(20,10))
ax = fig.add_subplot(111, projection='3d')

x = np.array(labels==0)
y = np.array(labels==1)
z = np.array(labels==2)


ax.scatter(X[x][:, 0], X[x][:, 1], X[x][:, 2], color='red')
ax.scatter(X[y][:, 0], X[y][:, 1], X[y][:, 2], color='blue')
ax.scatter(X[z][:, 0], X[z][:, 1], X[z][:, 2], color='yellow')
ax.scatter(centroids[:, 0], centroids[:, 1], centroids[:, 2],
            marker='x', s=169, linewidths=10,
            color='black', zorder=50)

enter image description here

import matplotlib.pyplot as plt
from sklearn.datasets import make_swiss_roll
from mpl_toolkits.mplot3d import Axes3D
X, t = make_swiss_roll(n_samples=1000, noise=0.2, random_state=42)
from sklearn.cluster import KMeans

kmeans = KMeans(n_clusters=3)                   # Number of clusters == 3
kmeans = kmeans.fit(X)                          # Fitting the input data
labels = kmeans.predict(X)                      # Getting the cluster labels
centroids = kmeans.cluster_centers_             # Centroid values
# print("Centroids are:", centroids)              # From sci-kit learn


fig = plt.figure(figsize=(10,10))
ax = fig.gca(projection='3d')

x = np.array(labels==0)
y = np.array(labels==1)
z = np.array(labels==2)


ax.scatter(centroids[:,0],centroids[:,1],centroids[:,2],c="black",s=150,label="Centers",alpha=1)
ax.scatter(X[x,0],X[x,1],X[x,2],c="blue",s=40,label="C1")
ax.scatter(X[y,0],X[y,1],X[y,2],c="yellow",s=40,label="C2")
ax.scatter(X[z,0],X[z,1],X[z,2],c="red",s=40,label="C3")

enter image description here

相关问题 更多 >