Visualizing Decision Trees in Machine Learning

Check previous blog as this is the continuation of the problem there: ilkecandan.hashnode.dev/persisting-models-i..

In this blog, we are going to explain our model, in a visual format so that we see how this model makes predictions.

For starters, our code should look like this:

import pandas as pd
from sklearn.tree import DecisionTreeClassifier
music=pd.read_csv('music.csv')
X = music.drop(columns=['genre'])
y= music['genre']

model=DecisionTreeClassifier()
model.fit(X,y)
music

It is pretty simple. It will show selections from our model. To import the data set click this link: bit.ly/3muqqta Now we are adding this line:

from sklearn import tree

This object has a method for graphically exporting our decision tree. After, the lines that we train our model we should add "tree".

tree.export_graphviz(model, out_file='music-recommender.dot', feature_names=['age', 'gender'], class_names=sorted(y.unique()),label='all', rounded=True, filled=True)

So final code looks like this:

import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree

music=pd.read_csv('music.csv')
X = music.drop(columns=['genre'])
y= music['genre']

model=DecisionTreeClassifier()
model.fit(X,y)

tree.export_graphviz(model, out_file='music-recommender.dot', feature_names=['age', 'gender'], class_names=sorted(y.unique()),label='all', rounded=True, filled=True)

Now, we can see that in our desktop there is file named 'music-recommender.dot'. You should simply drag it to Visual Studio Code. And, then dowload the "Graphviz (dot) language support for Visual Studio Code, João Pinto". It will be looking like this:

generating random values.png

After you see this screen, click to the three dots that I marked in the picture and select "Open Preview to the Side". You will see the respresentation of the decision tree.

data set me.png

This is the decision tree that our model uses to make predictions.