user9359930
user9359930

Reputation:

'RandomForestClassifier' object has no attribute 'tree_'

from sklearn.ensemble import RandomForestClassifier
from sklearn import tree

rf = RandomForestClassifier()

rf.fit(X_train, y_train)
n_nodes = rf.tree_.node_count

Everytime I run this code, I get the following error

'RandomForestClassifier' object has no attribute 'tree_'

any ideas why

Upvotes: 6

Views: 20012

Answers (3)

Alexander Michels
Alexander Michels

Reputation: 41

You want to pull a single DecisionTreeClassifier out of your forest. From the documentation, base_estimator_ is a DecisionTreeClassifier and estimators_ is a list of DecisionTreeClassifier. The change to your code is:

from sklearn.ensemble import RandomForestClassifier
from sklearn import tree

rf = RandomForestClassifier()

rf.fit(X_train, y_train)

n_nodes = rf.base_estimator_.tree_.node_count
  or
n_nodes = rf.estimators_[0].tree_.node_count

Upvotes: 4

ZEESHAN
ZEESHAN

Reputation: 319

'tree_' is not RandomForestClassifier attribute. It is the attribute of DecisionTreeClassifiers.

You should not use this while using RandomForestClassifier, there is no need of it.

Upvotes: 0

joaoavf
joaoavf

Reputation: 1383

According to scikit-learn documentation, it doesn't have .tree_ attribute.

It only has: estimators_, classes_, n_classes_, n_features_, n_outputs_, feature_importances_, oob_score_, and oob_decision_function_ attributes.

Upvotes: 4

Related Questions