首页 > 解决方案 > TypeError:需要一个类似字节的对象,而不是 Python 中 Image 命令的“str”

问题描述

我正在尝试在 Python 中加载决策树的图像,但我无法这样做。

代码是:

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

我收到以下错误:

TypeError:需要一个类似字节的对象,而不是 Python 中 Image 命令的“str”

您能否建议该Image命令出了什么问题?之前的print命令工作正常并且打印feature_importance完美。

标签: pythonimagedecision-tree

解决方案


我有同样的问题。我克隆了一个 github 文件夹,它出现了这个错误。我发现文件的名称不同。检查图像的路径是否正确。

import os
os.getwd()

此代码显示您的代码正在查找图像“park_tree.png”的目录。检查图像是否确实在目录中。你可以这样做

os.listdir()

这将显示当前目录中的每个文件。就我而言,文件的名称与代码中显示的名称不同。


推荐阅读