The data for this comes from the UCI machine learning repository Dua, D. and Graff, C. (2019). UCI Machine Learning Repository [http://archive.ics.uci.edu/ml]. Irvine, CA: University of California, School of Information and Computer Science.
This code runs without any technical error but whether I run it with None for out_file or give it a png file name it doesnt make the decision tree visual, instead it just prints it like this:
digraph Tree {
node [shape=box, style="filled", color="black", fontname="helvetica"] ;
edge [fontname="helvetica"] ;
0 [label="income_ >50K <= 0.5\ngini = 0.366\nsamples = 32561\nvalue = [24720,
7841]\nclass = i", fillcolor="#eda978"] ;
1 [label="gini = 0.0\nsamples = 24720\nvalue = [24720, 0]\nclass = i",
fillcolor="#e58139"] ;
0 -> 1 [labeldistance=2.5, labelangle=45, headlabel="True"] ;
2 [label="gini = 0.0\nsamples = 7841\nvalue = [0, 7841]\nclass = n",
fillcolor="#399de5"] ;
0 -> 2 [labeldistance=2.5, labelangle=-45, headlabel="False"] ;
}
here is my code
csv_file = age, workclass, fnlwgt, education, educationnum, maritalstatus, occupation,
relationship, race, sex, capitalgain, capitalloss, hoursperweek, nativecountry, income
39, State-gov, 77516, Bachelors, 13, Never-married, Adm-clerical, Not-in-family, White,
Male, 2174, 0, 40, United-States, <=50K
50, Self-emp-not-inc, 83311, Bachelors, 13, Married-civ-spouse, Exec-managerial,
Husband, White, Male, 0, 0, 13, United-States, <=50K
38, Private, 215646, HS-grad, 9, Divorced, Handlers-cleaners, Not-in-family, White,
Male, 0, 0, 40, United-States, <=50K
53, Private, 234721, 11th, 7, Married-civ-spouse, Handlers-cleaners, Husband, Black,
Male, 0, 0, 40, United-States, <=50K
########## alternative 2 ##########
import pandas as pd
import numpy as np
from sklearn.preprocessing import OneHotEncoder
import graphviz
# basic dataframe
dataframe = pd.read_csv(csv_file)
# cleaned up dataframe
dataframe.columns = dataframe.columns.str.strip()
# one hot encoded dataframe
ohe = pd.get_dummies(dataframe, columns=dataframe.columns)
# decision tree classifier
clf = tree.DecisionTreeClassifier(max_leaf_nodes=3)
clf = clf.fit(ohe, ohe['income_ >50K'])
# display for user
dot_data = tree.export_graphviz(clf, out_file=None,
feature_names=ohe.columns, class_names='income_ >50K',
filled=True)
graph = graphviz.Source(dot_data, format='png')
print(graph)
I am unsure how to proceed...