sklearn 上的 PCA - 如何解释 pca.components_

PCA on sklearn - how to interpret pca.components_

我 运行 使用此简单代码在具有 10 个特征的数据框中进行 PCA:

pca = PCA()
fit = pca.fit(dfPca)

pca.explained_variance_ratio_的结果显示:

array([  5.01173322e-01,   2.98421951e-01,   1.00968655e-01,
         4.28813755e-02,   2.46887288e-02,   1.40976609e-02,
         1.24905823e-02,   3.43255532e-03,   1.84516942e-03,
         4.50314168e-16])

我认为这意味着第一个 PC 解释了 52% 的方差,第二个分量解释了 29% 等等...

我不明白的是pca.components_的输出。如果我执行以下操作:

df = pd.DataFrame(pca.components_, columns=list(dfPca.columns))

我得到了下面的数据框,其中每一行都是一个主成分。 我想了解的是如何解释 table。我知道如果我对每个组件的所有特征进行平方并对它们求和,我会得到 1,但是 PC1 上的 -0.56 是什么意思?它是否说明了有关 "Feature E" 的信息,因为它是解释 52% 方差的分量的最高幅度?

谢谢

基本思路

你那里的按特征分类的主成分基本上告诉你 "direction" 每个主成分根据特征的方向指向。

在每个主成分中,具有更大绝对权重的特征 "pull" 主成分更倾向于该特征的方向。

例如我们可以说在PC1中,由于Feature A、Feature B、Feature I、Feature J的权重(绝对值)相对较低,PC1并没有那么多指向这些特征的方向在功能 space 中。相对于其他方向,PC1 将最指向要素 E 的方向。

低维可视化

要对此进行可视化,请查看以下摘自 here and here 的数字:

下面显示了运行 PCA 对相关数据的示例。

我们可以直观地看到从 PCA 导出的两个特征向量在特征 1 和特征 2 方向上都是 "pulled"。因此,如果我们要像您所做的那样对主要组件进行分解 table,我们希望从功能 1 和功能 2 中看到一些权重来解释 PC1 和 PC2。

接下来,我们有一个不相关数据的例子。

我们将绿色主成分称为PC1,将粉红色主成分称为PC2。很明显,PC1 没有被拉向特征 x' 的方向,PC2 也没有被拉向特征 y' 的方向。 因此,在我们的 table 中,PC1 中特征 x' 的权重必须为 0,PC2 中特征 y' 的权重必须为 0。

我希望这能让您了解您在 table 中看到的内容。

术语: 首先,PCA 的结果通常根据成分分数进行讨论,有时称为因子分数(对应于特定数据点的转换变量值) 和载荷(每个标准化原始变量应乘以得到组件分数的权重)。

第 1 部分:我解释了如何检查特征的重要性以及如何绘制双标图。

第 2 部分:我解释了如何检查特征的重要性以及如何使用特征名称将它们保存到 pandas 数据框中。

文章摘要:Python 精简指南:https://towardsdatascience.com/pca-clearly-explained-how-when-why-to-use-it-and-feature-importance-a-guide-in-python-7c274582c37e?source=friends_link&sk=65bf5440e444c24aff192fedf9f8b64f


第 1 部分:

在您的例子中,特征 E 的值 -0.56 是该特征在 PC1 上的得分。 这个值告诉我们 'how much' 该功能影响 PC(在我们的例子中是 PC1)。

所以绝对值越大,对主成分的影响越大

执行 PCA 分析后,人们通常绘制已知的 'biplot' 以查看 N 维(在我们的例子中为 2)的转换特征和原始变量(特征)。

我写了一个函数来绘制这个。


示例 使用虹膜数据:

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA

iris = datasets.load_iris()
X = iris.data
y = iris.target

#In general it is a good idea to scale the data
scaler = StandardScaler()
scaler.fit(X)
X=scaler.transform(X)

pca = PCA()
pca.fit(X,y)
x_new = pca.transform(X)   

def myplot(score,coeff,labels=None):
    xs = score[:,0]
    ys = score[:,1]
    n = coeff.shape[0]

    plt.scatter(xs ,ys, c = y) #without scaling
    for i in range(n):
        plt.arrow(0, 0, coeff[i,0], coeff[i,1],color = 'r',alpha = 0.5)
        if labels is None:
            plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, "Var"+str(i+1), color = 'g', ha = 'center', va = 'center')
        else:
            plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, labels[i], color = 'g', ha = 'center', va = 'center')

plt.xlabel("PC{}".format(1))
plt.ylabel("PC{}".format(2))
plt.grid()

#Call the function. 
myplot(x_new[:,0:2], pca. components_) 
plt.show()

结果

第 2 部分:

重要的特征是对成分影响较大的特征,因此在成分上具有较大的绝对值。

获取 PC 上最重要的特征 并使用名称将它们保存到 pandas 数据帧中 使用此方法:

from sklearn.decomposition import PCA
import pandas as pd
import numpy as np
np.random.seed(0)

# 10 samples with 5 features
train_features = np.random.rand(10,5)

model = PCA(n_components=2).fit(train_features)
X_pc = model.transform(train_features)

# number of components
n_pcs= model.components_.shape[0]

# get the index of the most important feature on EACH component
# LIST COMPREHENSION HERE
most_important = [np.abs(model.components_[i]).argmax() for i in range(n_pcs)]

initial_feature_names = ['a','b','c','d','e']
# get the names
most_important_names = [initial_feature_names[most_important[i]] for i in range(n_pcs)]

# LIST COMPREHENSION HERE AGAIN
dic = {'PC{}'.format(i): most_important_names[i] for i in range(n_pcs)}

# build the dataframe
df = pd.DataFrame(dic.items())

这会打印:

     0  1
 0  PC0  e
 1  PC1  d

所以在 PC1 上名为 e 的功能是最重要的,在 PC2 上名为 d.

文章总结: Python 精简指南:https://towardsdatascience.com/pca-clearly-explained-how-when-why-to-use-it-and-feature-importance-a-guide-in-python-7c274582c37e?source=friends_link&sk=65bf5440e444c24aff192fedf9f8b64f