简体   繁体   中英

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM