Hi I've found this code and I'm trying to plot a decision tree, but at the very end this "visualize_tree(test,columns)" give me an error: this is the code
from __future__ import print_function
import os
import subprocess
import pandas as pd
import numpy as np
from sklearn.tree import DecisionTreeClassifier, export_graphviz
y = test["churn"]
X = test[columns]
dt = DecisionTreeClassifier(min_samples_split=20, random_state=99)
dt.fit(X, y)
def visualize_tree(tree, feature_names):
"""Create tree png using graphviz.
Args
----
tree -- scikit-learn DecsisionTree.
feature_names -- list of feature names.
"""
with open("dt.dot", 'w') as f:
export_graphviz(tree, out_file=f,
feature_names=feature_names)
command = ["dot", "-Tpng", "dt.dot", "-o", "dt.png"]
try:
subprocess.check_call(command)
except:
exit("Could not run dot, ie graphviz, to "
"produce visualization")
visualize_tree(test,columns)
As I said only the very last line give me an error:
In[471]: visualize_tree(test,columns)
Traceback (most recent call last):
File "C:\Anaconda\lib\site-packages\IPython\core\interactiveshell.py", line 3066, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-471-ccc62a7b61d9>", line 1, in <module>
visualize_tree(test,columns)
File "<ipython-input-470-be9bd10e9f84>", line 81, in visualize_tree
feature_names=feature_names)
File "C:\Anaconda\lib\site-packages\sklearn\tree\export.py", line 403, in export_graphviz
recurse(decision_tree.tree_, 0, criterion=decision_tree.criterion)
File "C:\Anaconda\lib\site-packages\pandas\core\generic.py", line 2360, in __getattr__
(type(self).__name__, name))
AttributeError: 'DataFrame' object has no attribute 'tree_'