随机森林中每棵树的每个特征的特征重要性计算
Feature importance calculation for every features to every tree in Random Forest
我使用 python 库 sklearn.ensemble.RandomForestClassifier
。
我想知道每个特征对所有树的特征重要性。假设,我有 P
个特征和 M
个树。
我想计算 PxM
矩阵,其中计算每个特征对每棵树的特征重要性。
Here 是随机森林特征重要性的 sklearn 源代码。在这种方法中,我认为 all_importances
变量是 PxM 矩阵。但是我怎样才能访问那个变量呢?
提前致谢。
您可以使用 .estimators_
访问各个树,然后调用 feature_importances_
这是一个例子:
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=1000, n_features=4,
n_informative=2, n_redundant=0,
random_state=0, shuffle=False)
clf = RandomForestClassifier(n_estimators=5, max_depth=2,
random_state=0)
clf.fit(X, y)
feature_imp_ = [tree.feature_importances_.T for tree in clf.estimators_]
输出:
[array([0.02057642, 0.96636638, 0. , 0.01305721]),
array([0.86128406, 0. , 0.13871594, 0. ]),
array([0.00471007, 0.98648234, 0. , 0.00880759]),
array([0.02730208, 0.97269792, 0. , 0. ]),
array([0.65919044, 0.34080956, 0. , 0. ])]
我使用 python 库 sklearn.ensemble.RandomForestClassifier
。
我想知道每个特征对所有树的特征重要性。假设,我有 P
个特征和 M
个树。
我想计算 PxM
矩阵,其中计算每个特征对每棵树的特征重要性。
Here 是随机森林特征重要性的 sklearn 源代码。在这种方法中,我认为 all_importances
变量是 PxM 矩阵。但是我怎样才能访问那个变量呢?
提前致谢。
您可以使用 .estimators_
访问各个树,然后调用 feature_importances_
这是一个例子:
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=1000, n_features=4,
n_informative=2, n_redundant=0,
random_state=0, shuffle=False)
clf = RandomForestClassifier(n_estimators=5, max_depth=2,
random_state=0)
clf.fit(X, y)
feature_imp_ = [tree.feature_importances_.T for tree in clf.estimators_]
输出:
[array([0.02057642, 0.96636638, 0. , 0.01305721]),
array([0.86128406, 0. , 0.13871594, 0. ]),
array([0.00471007, 0.98648234, 0. , 0.00880759]),
array([0.02730208, 0.97269792, 0. , 0. ]),
array([0.65919044, 0.34080956, 0. , 0. ])]