1
votes

I'm trying to load the image of the Decision Tree in Python but I'm unable to do so.

The code is:

from IPython.display import Image  
#import pydotplus as pydot
from sklearn import tree
from os import system

train_char_label = ['1', '2']
park_Tree_File = open('park_tree.dot','w')
dot_data = tree.export_graphviz(dt_model, out_file=park_Tree_File, 
feature_names = list(train_set),
                                class_names = list(train_char_label))

park_Tree_File.close()

print (pd.DataFrame(dt_model.feature_importances_, columns = ["Imp"], index 
= train_set.columns))

system("dot -Tpng park_tree.dot -o park_tree.png") # This command is to OS
Image("park_tree.png") # use the image command to read the .png file 
                       # and print on screen

I get the following error:

TypeError: a bytes-like object is required, not 'str' for Image command in Python

Can you please suggest what is going wrong with the Image command? The print command before that is working fine and printing the feature_importance perfectly.

2
You forgot to tell people what is the error message you get? "File not found"? - Sheldore
The error message is in the question title - Sascha Gottfried

2 Answers

0
votes

I had the same problem. I've cloned a github folder and it was appearing this error. I've discovered that the name of the file was different. Check if the path for the image is correct.

import os
os.getwd()

This code shows the directory that your code is looking for the image "park_tree.png". check if the image is indeed in the directory. You can do that by doing

os.listdir()

This will show every file in the current directory. In my case, the name of the file was different of the name presented in the code.

0
votes

I faced a similar problem and found few workarounds.

  1. Try to change the absolute path of pwd. Keep it pretty simple (devoid of any numbers, special characters, space, etc.), this method worked out for me. Alternatively, if you don't want to change the pwd then try doing some manipulations of file path. Ref: check here

  2. In case you are using Jupyter notebook and require to insert the image only once, you can navigate to a Markdown cell > Edit (dropdown) > Insert image.