问题描述
from sklearn.ensemble import RandomForestRegressor
model=RandomForestRegressor()
model.fit(X_train,y_train)
model.score(X_test,y_test)
feature_list = list(X.columns)
r = export_text(model, feature_names=feature_list,
decimals=0, show_weights=True)
print(r)
AttributeError: 'RandomForestRegressor' object has no attribute 'tree_'
知道我在这里遗漏了什么吗?我正在尝试从随机森林回归器中获取树文本数据
Any idea what I'm missing here? I am trying to get tree text data out of a random forest regressor
推荐答案
RandomForestRegressor
是通过拟合多棵树来训练的,因此尝试直接export_text
没有意义> 来自分类器.事实上,正如错误指出的那样,它没有 tree_
属性.请注意,如 docs 中所述,它是曾经:
RandomForestRegressor
is trained by fitting multiple trees, hence it doesn't make sense to try to directly export_text
from the classifier. Indeed as the error points out, it does not have the attribute tree_
. Note that, as mentioned in the docs it is used to:
构建显示决策树
export_text
适用于决策树,因此如果您改为使用 RandomForest
的估计量之一作为 model
参数,它将起作用:
export_text
works with decision trees, so if you instead used one of the RandomForest
's estimators as model
argument it would work:
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import export_text
from sklearn.datasets import load_iris
iris = load_iris()
X = iris['data']
y = iris['target']
rf = RandomForestClassifier(random_state=0, max_depth=2)
rf.fit(X, y)
r = export_text(rf.estimators_[0], feature_names=iris['feature_names'])
print(r)
|--- petal width (cm) <= 0.75
| |--- class: 0.0
|--- petal width (cm) > 0.75
| |--- petal length (cm) <= 4.85
| | |--- class: 1.0
| |--- petal length (cm) > 4.85
| | |--- class: 2.0
当然,这只是被分类器拟合的估计量之一,并不代表分类器遵循的标准,即多棵树的集合.
Though of course this is only one of the estimators that have been fit by the classifier, and does not represent the criteria followed by the classifier, which is an ensemble of multiple trees.
这篇关于随机森林回归器,试图让树文本出来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!