简介
在本实验中,我们将使用随机森林来评估人工分类任务中特征的重要性。我们将生成一个仅包含 3 个信息性特征的合成数据集。将绘制森林的特征重要性,并绘制由误差线表示的树间变异性。
虚拟机提示
虚拟机启动完成后,点击左上角切换到“笔记本”标签,以访问 Jupyter Notebook 进行练习。
有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。
如果你在学习过程中遇到问题,请随时向 Labby 提问。课程结束后提供反馈,我们将立即为你解决问题。
导入库
我们将为本实验导入必要的库。
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance
import pandas as pd
import numpy as np
import time
生成数据
我们将生成一个仅包含 3 个信息性特征的合成数据集。我们将明确不打乱数据集,以确保信息性特征与 X 的前三列相对应。此外,我们将把数据集拆分为训练子集和测试子集。
X, y = make_classification(
n_samples=1000,
n_features=10,
n_informative=3,
n_redundant=0,
n_repeated=0,
n_classes=2,
random_state=0,
shuffle=False,
)
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42)
拟合随机森林
我们将拟合一个随机森林分类器来计算特征重要性。
feature_names = [f"feature {i}" for i in range(X.shape[1])]
forest = RandomForestClassifier(random_state=0)
forest.fit(X_train, y_train)
基于杂质平均减少量的特征重要性
拟合属性feature_importances_提供了特征重要性,它们是通过计算每棵树内杂质减少量累积的均值和标准差来得到的。我们将绘制基于杂质的重要性。
start_time = time.time()
importances = forest.feature_importances_
std = np.std([tree.feature_importances_ for tree in forest.estimators_], axis=0)
elapsed_time = time.time() - start_time
print(f"Elapsed time to compute the importances: {elapsed_time:.3f} seconds")
forest_importances = pd.Series(importances, index=feature_names)
fig, ax = plt.subplots()
forest_importances.plot.bar(yerr=std, ax=ax)
ax.set_title("Feature importances using MDI")
ax.set_ylabel("Mean decrease in impurity")
fig.tight_layout()
基于特征排列的特征重要性
排列特征重要性克服了基于杂质的特征重要性的局限性:它们对高基数特征没有偏差,并且可以在留出的测试集上计算。我们将计算完整的排列重要性。特征被随机打乱 n 次,并且重新拟合模型以估计其重要性。我们将绘制重要性排名。
start_time = time.time()
result = permutation_importance(
forest, X_test, y_test, n_repeats=10, random_state=42, n_jobs=2
)
elapsed_time = time.time() - start_time
print(f"Elapsed time to compute the importances: {elapsed_time:.3f} seconds")
forest_importances = pd.Series(result.importances_mean, index=feature_names)
fig, ax = plt.subplots()
forest_importances.plot.bar(yerr=result.importances_std, ax=ax)
ax.set_title("Feature importances using permutation on full model")
ax.set_ylabel("Mean accuracy decrease")
fig.tight_layout()
plt.show()
总结
在本实验中,我们生成了一个仅包含 3 个信息性特征的合成数据集,并使用随机森林来评估特征的重要性。我们绘制了森林的特征重要性,以及由误差线表示的树间变异性。我们使用基于杂质的重要性和特征排列重要性来计算特征重要性。两种方法都检测到相同的特征为最重要的特征。