I am trying to use the random forest model to predict social media ads effects based on age and estimated salary, this is my code but i keep getting Attribute error prompting up.
from sklearn.tree import export_graphviz
from IPython import display
from sklearn.ensemble import RandomForestRegressor
m = RandomForestRegressor(n_estimators=5, max_depth=3, bootstrap=False, n_jobs=-1)
m.fit(x_train, y_train)
# data = data.drop('Purchased', axis=1)
str_tree = export_graphviz(m,
out_file=None,
feature_names=data.columns[2:4],
filled=True,
special_characters=True,
rotate=True,
precision=1)
display.display(str_tree)
This is the error i keep getting. Despite the fact that i didn't call the tree_ parameter.
File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\sklearn\tree\_export.py:465, in _DOTTreeExporter.export(self, decision_tree)
463 self.recurse(decision_tree, 0, criterion="impurity")
464 else:
--> 465 self.recurse(decision_tree.tree_, 0, criterion=decision_tree.criterion)
467 self.tail()
AttributeError: 'RandomForestRegressor' object has no attribute 'tree_'
graphvizworks with individual trees. You can access the fitted decision trees of the random forest via its.estimators_attribute:fitted_trees = random_forest.estimators_.For displaying, I think you'll also need to run
sudo apt install graphvizand usegraphviz.Source(dot_string). I've included a few options for displaying the graph. By default, the graph can be very wide, so I prefer to handle its size before rendering the plot.Example with sample data: