python - PCA 分析后的特征/变量重要性
问题描述
我已经对我的原始数据集进行了 PCA 分析,并且从由 PCA 转换的压缩数据集中,我还选择了我想要保留的 PC 数量(它们解释了几乎 94% 的方差)。现在我正在努力识别在缩减数据集中很重要的原始特征。如何找出降维后剩余的主成分中哪些特征是重要的,哪些不是?这是我的代码:
from sklearn.decomposition import PCA
pca = PCA(n_components=8)
pca.fit(scaledDataset)
projection = pca.transform(scaledDataset)
此外,我还尝试在减少的数据集上执行聚类算法,但令我惊讶的是,分数低于原始数据集。这怎么可能?
解决方案
首先,我假设您调用features
变量和not the samples/observations
. 在这种情况下,您可以通过创建一个biplot
在一个图中显示所有内容的函数来执行以下操作。在此示例中,我使用的是 iris 数据。
在示例之前,请注意使用 PCA 作为特征选择工具时的基本思想是根据其系数(载荷)的大小(绝对值从大到小)来选择变量。有关更多详细信息,请参阅情节后的最后一段。
概述:
第 1部分:我解释了如何检查特征的重要性以及如何绘制双标图。
第2 部分:我解释了如何检查特征的重要性以及如何使用特征名称将它们保存到 pandas 数据框中。
第1部分:
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.decomposition import PCA
import pandas as pd
from sklearn.preprocessing import StandardScaler
iris = datasets.load_iris()
X = iris.data
y = iris.target
#In general a good idea is to scale the data
scaler = StandardScaler()
scaler.fit(X)
X=scaler.transform(X)
pca = PCA()
x_new = pca.fit_transform(X)
def myplot(score,coeff,labels=None):
xs = score[:,0]
ys = score[:,1]
n = coeff.shape[0]
scalex = 1.0/(xs.max() - xs.min())
scaley = 1.0/(ys.max() - ys.min())
plt.scatter(xs * scalex,ys * scaley, c = y)
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.xlim(-1,1)
plt.ylim(-1,1)
plt.xlabel("PC{}".format(1))
plt.ylabel("PC{}".format(2))
plt.grid()
#Call the function. Use only the 2 PCs.
myplot(x_new[:,0:2],np.transpose(pca.components_[0:2, :]))
plt.show()
使用 biplot 可视化正在发生的事情
现在,每个特征的重要性通过特征向量中相应值的大小来反映(更高的大小 - 更高的重要性)
让我们首先看看每台 PC 解释了多少差异。
pca.explained_variance_ratio_
[0.72770452, 0.23030523, 0.03683832, 0.00515193]
PC1 explains 72%
和PC2 23%
。一起,如果我们只保留 PC1 和 PC2,他们会解释95%
.
现在,让我们找到最重要的功能。
print(abs( pca.components_ ))
[[0.52237162 0.26335492 0.58125401 0.56561105]
[0.37231836 0.92555649 0.02109478 0.06541577]
[0.72101681 0.24203288 0.14089226 0.6338014 ]
[0.26199559 0.12413481 0.80115427 0.52354627]]
这里,pca.components_
有形[n_components, n_features]
。因此,通过查看PC1
第一行的(第一主成分):[0.52237162 0.26335492 0.58125401 0.56561105]]
我们可以得出结论feature 1, 3 and 4
(或双图中的 Var 1、3 和 4)是最重要的。这在双标图上也清晰可见(这就是我们经常使用此图以直观方式总结信息的原因)。
综上所述,查看与 k 个最大特征值相对应的特征向量分量的绝对值。在sklearn
组件中按 排序explained_variance_
。这些绝对值越大,特定特征对该主成分的贡献就越大。
第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
.
推荐阅读
- javascript - 在 JavaScript 中同步加载和评估动态生成的脚本
- admob - 为什么我什至没有尝试使用与 AdMob 远程链接的任何东西时,AdMob 会搞砸我的基本音乐播放/暂停应用
- typescript - , IntelliJ 如何支持一些 TypeScript 编译器不支持的特性?
- string - 对字符串数组进行排序,以便稍后出现任何其他字符串的子字符串
- r - R使用循环将多个图表绘制为单个pdf
- python - 如何计算字符串中所有值的频率/出现次数
- typescript - 如何在声明文件的命名空间中键入循环引用?
- excel - 通过 vba 导入 csv 时将数字类型更改为文本类型
- mysql - MySQL 数据库中 SHOW TABLE STATUS 的 `engine` 列中的 NULL 是什么意思?
- r - 如何使用 dplyr 根据函数结果创建新变量以产生分组数据?