Python中PCA图中的项目变量

Ale*_*hez 1 python r pca

在R中执行PCA分析后,我们可以:

ggbiplot(pca, choices=1:2, groups=factor(row.names(df_t)))
Run Code Online (Sandbox Code Playgroud)

这将绘制2个PC空间中的数据,以及诸如矢量(具有不同长度和方向)的空间中的变量的方向和权重.

在Python中我可以在2个PC空间中绘制数据,我可以得到变量的权重,但我如何知道方向.

换句话说,我怎样才能在Python中绘制对PC(重量和方向)的变量贡献?

Who*_*ack 5

我不知道任何预先实现的这种情节,但它可以使用matplotlib.pyplot.quiver.这是我快速整理的一个例子.您可以使用此作为基础来创建适合您的数据的漂亮绘图.


示例数据

这会生成一些示例数据.它从这个答案中重复使用.

# User input
n_samples  = 100
n_features =   5

# Prep
data  = np.empty((n_samples,n_features))
np.random.seed(42)

# Generate
for i,mu in enumerate(np.random.choice([0,1,2,3], n_samples, replace=True)):
    data[i,:] = np.random.normal(loc=mu, scale=1.5, size=n_features)
Run Code Online (Sandbox Code Playgroud)

PCA

pca = PCA().fit(data)
Run Code Online (Sandbox Code Playgroud)

变量因子图

开始了:

# Get the PCA components (loadings)
PCs = pca.components_

# Use quiver to generate the basic plot
fig = plt.figure(figsize=(5,5))
plt.quiver(np.zeros(PCs.shape[1]), np.zeros(PCs.shape[1]),
           PCs[0,:], PCs[1,:], 
           angles='xy', scale_units='xy', scale=1)

# Add labels based on feature names (here just numbers)
feature_names = np.arange(PCs.shape[1])
for i,j,z in zip(PCs[1,:]+0.02, PCs[0,:]+0.02, feature_names):
    plt.text(j, i, z, ha='center', va='center')

# Add unit circle
circle = plt.Circle((0,0), 1, facecolor='none', edgecolor='b')
plt.gca().add_artist(circle)

# Ensure correct aspect ratio and axis limits
plt.axis('equal')
plt.xlim([-1.0,1.0])
plt.ylim([-1.0,1.0])

# Label axes
plt.xlabel('PC 0')
plt.ylabel('PC 1')

# Done
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


不确定

我对箭头的缩放有点挣扎.请确保它们正确反映了您的数据的加载量.快速检查是否feature 4真正与PC 1(如本例所示)强烈关联看起来很有希望:

data_pca = pca.transform(data)
plt.scatter(data_pca[:,1], data[:,4])
plt.xlabel('PC 2') and plt.ylabel('feature 4')
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述