Reputation: 91
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
Upvotes: 0
Views: 1472
Reputation: 88305
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:
Build a text report showing the rules of a decision tree
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.
Upvotes: 4