Scikit learn 如何从经过训练的随机森林中找到关键树/特征?
我正在使用Scikit学习随机森林分类器,并试图提取有意义的树/特征,以便更好地理解预测结果 我在文档()中找到了这个方法,但找不到如何使用它的示例 我也希望能够可视化这些树,如果可能的话,任何相关的代码都会很好Scikit learn 如何从经过训练的随机森林中找到关键树/特征?,scikit-learn,Scikit Learn,我正在使用Scikit学习随机森林分类器,并试图提取有意义的树/特征,以便更好地理解预测结果 我在文档()中找到了这个方法,但找不到如何使用它的示例 我也希望能够可视化这些树,如果可能的话,任何相关的代码都会很好 谢谢大家! 要获得相关特征的重要性,请阅读该部分中链接示例的代码 树本身存储在随机林实例的估计器属性中(仅在调用fit方法之后)。现在要提取一个“关键树”,首先需要定义它是什么,以及希望用它做什么 你可以通过计算测试集上的分数来对各个树进行排序,但我不知道你能从中得到什么 你想通过减少
谢谢大家! 要获得相关特征的重要性,请阅读该部分中链接示例的代码 树本身存储在随机林实例的
估计器
属性中(仅在调用fit
方法之后)。现在要提取一个“关键树”,首先需要定义它是什么,以及希望用它做什么
你可以通过计算测试集上的分数来对各个树进行排序,但我不知道你能从中得到什么
你想通过减少树的数量而不降低聚合林的准确性来修剪森林以使预测更快吗?我认为你在寻找森林。功能\u重要性\u。这允许您查看每个输入特性对最终模型的相对重要性。这里有一个简单的例子
import random
import numpy as np
from sklearn.ensemble import RandomForestClassifier
#Lets set up a training dataset. We'll make 100 entries, each with 19 features and
#each row classified as either 0 and 1. We'll control the first 3 features to artificially
#set the first 3 features of rows classified as "1" to a set value, so that we know these are the "important" features. If we do it right, the model should point out these three as important.
#The rest of the features will just be noise.
train_data = [] ##must be all floats.
for x in range(100):
line = []
if random.random()>0.5:
line.append(1.0)
#Let's add 3 features that we know indicate a row classified as "1".
line.append(.77)
line.append(.33)
line.append(.55)
for x in range(16):#fill in the rest with noise
line.append(random.random())
else:
#this is a "0" row, so fill it with noise.
line.append(0.0)
for x in range(19):
line.append(random.random())
train_data.append(line)
train_data = np.array(train_data)
# Create the random forest object which will include all the parameters
# for the fit. Make sure to set compute_importances=True
Forest = RandomForestClassifier(n_estimators = 100, compute_importances=True)
# Fit the training data to the training output and create the decision
# trees. This tells the model that the first column in our data is the classification,
# and the rest of the columns are the features.
Forest = Forest.fit(train_data[0::,1::],train_data[0::,0])
#now you can see the importance of each feature in Forest.feature_importances_
# these values will all add up to one. Let's call the "important" ones the ones that are above average.
important_features = []
for x,i in enumerate(Forest.feature_importances_):
if i>np.average(Forest.feature_importances_):
important_features.append(str(x))
print 'Most important features:',', '.join(important_features)
#we see that the model correctly detected that the first three features are the most important, just as we expected!
以下是我如何想象这棵树: 完成所有预处理、拆分等后,首先制作模型:
# max number of trees = 100
from sklearn.ensemble import RandomForestClassifier
classifier = RandomForestClassifier(n_estimators = 100, criterion = 'entropy', random_state = 0)
classifier.fit(X_train, y_train)
作出预测:
# Predicting the Test set results
y_pred = classifier.predict(X_test)
然后画出重要的情节。变量dataset
是原始数据帧的名称
# get importances from RF
importances = classifier.feature_importances_
# then sort them descending
indices = np.argsort(importances)
# get the features from the original data set
features = dataset.columns[0:26]
# plot them with a horizontal bar chart
plt.figure(1)
plt.title('Feature Importances')
plt.barh(range(len(indices)), importances[indices], color='b', align='center')
plt.yticks(range(len(indices)), features[indices])
plt.xlabel('Relative Importance')
这将生成如下图:
非常感谢您的详细回答!我的目标是找出哪些功能更具影响力,因为我正在尝试设计新功能,并希望看到它们的性能如何,同时我还可以优化林的速度和大小,如您所述。由于特征组合的行为可能不同于它们各自的重要性,因此我考虑搜索性能最好的树(度量将是它们的预测误差的函数)。我假设这是拟合过程的一部分,对于每个预测中的树权重?在随机森林中,没有树权重。所有的树都是平等的。这是增强树的一个主要区别。对,很抱歉。我试图理解重要性是如何计算的,在“compute\u feature\u importances()”下的“\u tree.pyx”中的代码是正确的吗?如果是这样的话,请告诉我n_样本、初始错误和最佳错误是什么?这是我自己,但我不熟悉它,因此我无法立即回答。似乎不再支持
compute_importances
。“feature_importances”似乎是sklearn.employee.RandomForestClassifier v0.17的新属性。