我无法用所需的彩色群集绘制图形。 每个点都属于一个特定的群集,因此每个群集应具有特定的颜色,但是如图所示,我无法获得所需的颜色。如何修改代码以获得预期的结果和良好的群集。
pca_ = PCA(n_components=3)
X_Demo_fit_pca = pca_.fit_transform(Demo_df_Processed)
kmeans_PCA = KMeans(n_clusters=4, init='k-means++', max_iter= 300, n_init= 10, random_state= 3)
y_kmeans_PCA = kmeans_PCA.fit_predict(X_Demo_fit_pca)
y_kmeans_PCA
Demo_df_Processed.head()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X_Demo_fit_pca[:,0],X_Demo_fit_pca[:,1],X_Demo_fit_pca[:,2], c=y,
edgecolor='k', s=40, alpha = 0.5)
ax.set_title("First three PCA directions")
ax.set_xlabel("Educational_Degree")
ax.set_ylabel("Gross_Monthly_Salary")
ax.set_zlabel("Claim_Rate")
ax.dist = 10
ax.scatter(kmeans.cluster_centers_[:,0], kmeans.cluster_centers_[:,1], kmeans.cluster_centers_[:,2],
s = 100, c = 'r', label = 'Centroid')
plt.autoscale(enable=True, axis='x', tight=True)
plt.show()
答案 0 :(得分:1)
随着一些随机生成的数据和代码中的一些更改,我想这就是您想要的(特定群集中的每个数据点具有相同的颜色):
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# randomly generate some data with 4 distinct clusters, use your own data here
Demo_df_Processed = pd.DataFrame(np.random.randint(-2100,-2000,size=(100, 4)), columns=list('ABCD'))
Demo_df_Processed = Demo_df_Processed.append(pd.DataFrame(np.random.randint(-600,-500,size=(100, 4)), columns=list('ABCD')))
Demo_df_Processed = Demo_df_Processed.append(pd.DataFrame(np.random.randint(500,600,size=(100, 4)), columns=list('ABCD')))
Demo_df_Processed = Demo_df_Processed.append(pd.DataFrame(np.random.randint(2000,2100,size=(100, 4)), columns=list('ABCD')))
pca_ = PCA(n_components=3)
X_Demo_fit_pca = pca_.fit_transform(Demo_df_Processed)
kmeans_PCA = KMeans(n_clusters=4, init='k-means++', max_iter= 300, n_init= 10, random_state= 3)
y_kmeans_PCA = kmeans_PCA.fit_predict(X_Demo_fit_pca)
y_kmeans_PCA
fig = plt.figure(figsize=(20,10))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X_Demo_fit_pca[:,0],X_Demo_fit_pca[:,1],X_Demo_fit_pca[:,2],
c=y_kmeans_PCA, cmap='viridis',
edgecolor='k', s=40, alpha = 0.5)
ax.set_title("First three PCA directions")
ax.set_xlabel("Educational_Degree")
ax.set_ylabel("Gross_Monthly_Salary")
ax.set_zlabel("Claim_Rate")
ax.dist = 10
ax.scatter(kmeans_PCA.cluster_centers_[:,0], kmeans_PCA.cluster_centers_[:,1],
kmeans_PCA.cluster_centers_[:,2],
s = 300, c = 'r', marker='*', label = 'Centroid')
plt.autoscale(enable=True, axis='x', tight=True)
plt.show()