如何在 Python scikit-learn 中输出随机森林中每棵树的回归预测?

Ker*_*mit 3 python regression machine-learning random-forest scikit-learn

我是 scikit-learn 和随机森林回归的新手,想知道除了组合预测之外,是否有一种简单的方法可以从随机森林中的每棵树获得预测。

基本上我想在 R 中使用该predict.all = True选项可以做什么。


# Import the model we are using
from sklearn.ensemble import RandomForestRegressor
# Instantiate model with 1000 decision trees
rf = RandomForestRegressor(n_estimators = 1000, random_state = 1337)
# Train the model on training data
rf.fit(train_features, train_labels)
# Use the forest's predict method on the test data
predictions = rf.predict(test_features)
print(len(predictions)) #6565 which is the number of observations my test set has.
Run Code Online (Sandbox Code Playgroud)

我想对每棵树进行每一次预测,而不仅仅是每个预测的平均值。

可以在python中做到吗?

Jon*_*oop 6

import numpy as np
predictions_all = np.array([tree.predict(X) for tree in rf.estimators_])
print(predictions_all.shape) #(1000, 6565) 1000 rows: one for every Tree, 6565 columns, one for every target
Run Code Online (Sandbox Code Playgroud)

这使用estimators_-attribute(参见Docs),它是所有经过训练的DecisionTreeRegressors的列表。然后我们可以对它们中的每一个调用 predict 方法并将其保存到一个数组中。