【问题标题】:Plot a Correlation Circle in Python在 Python 中绘制相关圆
【发布时间】:2016-10-15 10:05:42
【问题描述】:

我一直在做一些几何数据分析 (GDA),例如主成分分析 (PCA)。我正在寻找一个相关圈......这些看起来有点像这样:

基本上,它允许测量变量的特征值/特征向量与数据集的主成分(维度)相关的扩展程度。

有人知道是否有 python 包可以绘制这种数据可视化吗?

【问题讨论】:

标签: python correlation pca eigenvalue eigenvector


【解决方案1】:

这是一个使用 sklearn 和 iris 数据集的简单示例。包括前两个维度的因子图和碎石图:

from sklearn.decomposition import PCA
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
 
df = sns.load_dataset('iris')
 
n_components = 4
 
# Do the PCA.
pca = PCA(n_components=n_components)
reduced = pca.fit_transform(df[['sepal_length', 'sepal_width',
                                'petal_length', 'petal_width']])

# Append the principle components for each entry to the dataframe
for i in range(0, n_components):
    df['PC' + str(i + 1)] = reduced[:, i]

display(df.head())

# Do a scree plot
ind = np.arange(0, n_components)
(fig, ax) = plt.subplots(figsize=(8, 6))
sns.pointplot(x=ind, y=pca.explained_variance_ratio_)
ax.set_title('Scree plot')
ax.set_xticks(ind)
ax.set_xticklabels(ind)
ax.set_xlabel('Component Number')
ax.set_ylabel('Explained Variance')
plt.show()

# Show the points in terms of the first two PCs
g = sns.lmplot('PC1',
               'PC2',
               hue='species',data=df,
               fit_reg=False,
               scatter=True,
               size=7)

plt.show()

# Plot a variable factor map for the first two dimensions.
(fig, ax) = plt.subplots(figsize=(8, 8))
for i in range(0, pca.components_.shape[1]):
    ax.arrow(0,
             0,  # Start the arrow at the origin
             pca.components_[0, i],  #0 for PC1
             pca.components_[1, i],  #1 for PC2
             head_width=0.1,
             head_length=0.1)

    plt.text(pca.components_[0, i] + 0.05,
             pca.components_[1, i] + 0.05,
             df.columns.values[i])


an = np.linspace(0, 2 * np.pi, 100)
plt.plot(np.cos(an), np.sin(an))  # Add a unit circle for scale
plt.axis('equal')
ax.set_title('Variable factor map')
plt.show()

将其扩展到更多的 PC 是一个很好的练习,如果所有组件都很小,则可以处理缩放问题,并避免绘制贡献最小的因子。

【讨论】:

  • 感谢这一点 - 一个变化,绘制变量因子图的循环应该超过特征的数量,而不是组件的数量。应该是 range(pca.components_.shape[1]),而不是 range(0, len(pca.components_))。
【解决方案2】:

我同意在 sklearn 等主流软件包中没有它是一种遗憾。

这是一个自制的实现: https://github.com/mazieres/analysis/blob/master/analysis.py#L19-34

【讨论】:

  • 是的,这非常适合 mlxtend。为什么不提交 PR Christophe?
猜你喜欢
  • 2021-01-19
  • 2020-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-18
相关资源
最近更新 更多