如何绘制不同颜色的 3D PCA?
Posted
技术标签:
【中文标题】如何绘制不同颜色的 3D PCA?【英文标题】:How to plot 3D PCA with different colors? 【发布时间】:2021-03-22 07:23:48 【问题描述】:让我们获取以下数据:
import numpy as np
from sklearn.datasets import load_breast_cancer
import pandas as pd
from sklearn.decomposition import PCA
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
让我们考虑数据
data = load_breast_cancer()
X = data.data
y = data.target
sc = StandardScaler()
我想用 3 个分量绘制 PCA 的 3D 图,但我只能为前两个分量绘制。
我目前的工作
scaler=StandardScaler()
scaler.fit(X)
X_scaled=scaler.transform(X)
pca=PCA(n_components=3)
pca.fit(X_scaled)
X_pca=pca.transform(X_scaled)
ex_variance=np.var(X_pca,axis=0)
ex_variance_ratio = ex_variance/np.sum(ex_variance)
ex_variance_ratio
Xax=X_pca[:,0]
Yax=X_pca[:,1]
cdict=0:'red',1:'green'
labl=0:'Malignant',1:'Benign'
marker=0:'*',1:'o'
alpha=0:.3, 1:.5
fig,ax=plt.subplots(figsize=(7,5))
fig.patch.set_facecolor('white')
for l in np.unique(y):
ix=np.where(y==l)
ax.scatter(Xax[ix],Yax[ix],c=cdict[l],s=40,
label=labl[l],marker=marker[l],alpha=alpha[l])
# for loop ends
plt.xlabel("First Principal Component",fontsize=14)
plt.ylabel("Second Principal Component",fontsize=14)
plt.legend()
plt.show()
在输出中我们得到:
您知道如何为第三个主要组件执行此操作吗?当然它应该是 3D,但我不知道该怎么做......
【问题讨论】:
【参考方案1】:其实很简单-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.datasets import load_breast_cancer
from sklearn.decomposition import PCA
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
# %matplotlib notebook
data = load_breast_cancer()
X = data.data
y = data.target
sc = StandardScaler()
scaler = StandardScaler()
scaler.fit(X)
X_scaled = scaler.transform(X)
pca = PCA(n_components=3)
pca.fit(X_scaled)
X_pca = pca.transform(X_scaled)
ex_variance=np.var(X_pca,axis=0)
ex_variance_ratio = ex_variance/np.sum(ex_variance)
ex_variance_ratio
Xax = X_pca[:,0]
Yax = X_pca[:,1]
Zax = X_pca[:,2]
cdict = 0:'red',1:'green'
labl = 0:'Malignant',1:'Benign'
marker = 0:'*',1:'o'
alpha = 0:.3, 1:.5
fig = plt.figure(figsize=(7,5))
ax = fig.add_subplot(111, projection='3d')
fig.patch.set_facecolor('white')
for l in np.unique(y):
ix=np.where(y==l)
ax.scatter(Xax[ix], Yax[ix], Zax[ix], c=cdict[l], s=40,
label=labl[l], marker=marker[l], alpha=alpha[l])
# for loop ends
ax.set_xlabel("First Principal Component", fontsize=14)
ax.set_ylabel("Second Principal Component", fontsize=14)
ax.set_zlabel("Third Principal Component", fontsize=14)
ax.legend()
plt.show()
这就是你所追求的吗?
【讨论】:
你太棒了!正是我想要的! 谢谢,但您确实完成了大部分工作! =)以上是关于如何绘制不同颜色的 3D PCA?的主要内容,如果未能解决你的问题,请参考以下文章