随机森林回归器,尝试获取树木文本

2024-04-27 00:16:00 发布

您现在位置:Python中文网/ 问答频道 /正文

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_'

你知道我错过了什么吗?我试图从随机森林回归器中获取树文本数据


Tags: columnstextfromtestimportmodeltrainexport
1条回答
网友
1楼 · 发布于 2024-04-27 00:16:00

RandomForestRegressor是通过拟合多个树来训练的,因此尝试直接从分类器中export_text是没有意义的。事实上,正如错误所指出的,它没有属性tree_。注意,如docs中所述,它用于:

Build a text report showing the rules of a decision tree

export_text适用于决策树,因此,如果改用RandomForest的一个估计器作为model参数,它将起作用:

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

当然,这是分类器拟合的估计器之一,并不代表分类器遵循的标准,分类器是多个树的ensemble

相关问题 更多 >