【问题标题】:How to output the regression prediction from each tree in a Random Forest in Python scikit-learn?如何在 Python scikit-learn 中输出随机森林中每棵树的回归预测?
【发布时间】:2020-02-12 05:40:02
【问题描述】:

我是 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.

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

在python中可以做到吗?

【问题讨论】:

    标签: python machine-learning scikit-learn regression random-forest


    【解决方案1】:

    使用

    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
    

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

    【讨论】:

      猜你喜欢
      • 2014-04-20
      • 2022-01-12
      • 2017-03-26
      • 2016-05-27
      • 2015-02-20
      • 2013-04-26
      相关资源
      最近更新 更多