I want to visualize each of the Decision Tree in the Random Forest. For which the code is as below:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
boston=load_boston()
boston_df=pd.DataFrame(boston.data,columns=boston.feature_names)
boston_df['Price']=boston.target
newX=boston_df.drop('Price',axis=1)
newY=boston_df['Price']
X_train, X_test, y_train, y_test = train_test_split(newX, newY, test_size=0.2)
from sklearn.ensemble import RandomForestRegressor
original_regressor = RandomForestRegressor(n_estimators = 10, random_state = 0)
original_regressor.fit(X_train, y_train)
from sklearn.tree import export_graphviz
from sklearn.externals.six import StringIO
from IPython.display import Image
import pydotplus
dot_data = StringIO()
for tree_in_forest in original_regressor.estimators_:
export_graphviz(tree_in_forest, out_file=dot_data, filled=True, rounded=True, special_characters=True,feature_names = ['CRIM', 'ZN','INDUS','CHAS','NOX','RM','AGE','DIS','RAD','TAX','PTRATIO','B','LSTAT'], node_ids = True)
graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
Image(graph.create_png())
The error I am getting is:
AttributeError: 'list' object has no attribute 'create_png'
Most of the solutions is updating the package from pydot
to pydotplus
. In my case, I am already using pydotplus
. Here the function pydot.graph_from_dot_data
returns a list if there are multiple graphs. I am assuming the error is because of this. If so, how do we solve this problem?