Skip to main content
 首页 » 编程设计

python之为什么在使用 PCA 减少后拟合随机森林模型时性能会受到影响

2025年05月04日19arxive

这个问题是关于在执行 PCA 后比较完整特征集上的随机森林分类器模型与减少组件数量的随机森林模型之间的速度。我使用的 MNIST 数据集有 60,000 行用于我的训练 (X_train) 和 10,000 行用于我的测试 (X_test),还有 784 个特征,这些特征是代表 28x28 图像的像素。

对于全套功能,我正在测量使用 clock() 来适应所需的时间,如下所示:

clf = RandomForestClassifier() 
t0 = time.clock() 
clf.fit(X_train, y_train) 
runtime = time.clock() - t0 

为了做 PCA 和随机森林,我正在做类似的事情:

pca = PCA(n_components = 0.95) 
t0 = time.clock() 
components = pca.fit_transform(X_train) 
clf.fit(components, y_train) 
runtime = time.clock() - t0 

对于全套,我得到了大约 6 秒的运行时间,而对于第二组,我得到了大约 27 秒的运行时间。即使我单独查看拟合的运行时间(除去执行 pca 所需的时间),我仍然始终得到大约 6 秒而不是 14 秒。全套的特征数量为 784,而 PCA 将其减少到 154 个组件。我有限的理解是,至少,由于特征数量减少,使用 PCA 拟合模型应该更快 - 为什么不呢?

我尝试过在 PCA 之前进行缩放、调整超参数等,但它与运行时的反直觉差异非常一致,我相信我在概念上不理解某些东西。

请您参考如下方法:

功能差异

你说你本来有784的特征,但你把它减少到154。这可能看起来很多。但是,如果您查看文档:

max_features : int, float, string or None, optional (default=”auto”)

The number of features to consider when looking for the best split:

  • If “auto”, then max_features=sqrt(n_features).

这意味着您的原始问题是 sqrt(784) = 28 并且您将其减少为 sqrt(154) = 12。

是的,现在变小了,但没有你原来想象的那么小。

优化

构建随机森林的方式是查看可能的分割并根据特定标准选择最佳分割。注意文档:

criterion : string, optional (default=”gini”)

The function to measure the quality of a split. Supported criteria are “gini” for the Gini impurity and “entropy” for the information gain. Note: this parameter is tree-specific.

[...]

Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than max_features features.

因此,在拟合时,算法会迭代优化标准的可能拆分。但是,通过减少特征的数量,您可能会使找到此拆分的问题变得更加困难(通过找到更少的好的拆分),这使得算法需要更多的迭代才能找到好的拆分。