微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

保存 IPython.core.display.Image 对象

如何解决保存 IPython.core.display.Image 对象

我有一个格式为 <IPython.core.display.Image object>文件,我收到如下:

graph = uplift_tree_plot (uplift_model.fitted_uplift_tree,x_names)
img = Image (graph.create_png ())

如何保存这张 png 图片

解决方法

您似乎在使用 causalml 生成 graph,因此通过检查 uplift_tree_plot() 的源代码,我们可以看到它返回了 {{1} 提供的某个类的对象}} 包:

pydotplus

def uplift_tree_plot(decisionTree,x_names): ''' Convert the tree to dot graph for plots. Args ---- decisionTree : object object of DecisionTree class x_names : list List of feature names Returns ------- Dot class representing the tree graph. ''' ... graph = pydotplus.graph_from_dot_data(dot_data) return graph API 文档对于了解该对象可以做什么也不是很有帮助,因此我们也可以inspect its source 了解 API 提供了什么。事实证明,这种编写方式很难搜索我们关心的函数,因为它会动态生成其中一些函数,但是 pydotplus 设置函数以呈现各种格式的图像,委托给 Dot.__init__在调用 Dot.create 时进行实际渲染。该函数至少有一些文档:

create_png

因此,由于此函数返回渲染文件的内容,因此您可以简单地将返回的字节串 def create(self,prog=None,format='ps'): """Creates and returns a Postscript representation of the graph. create will write the graph to a temporary dot file and process it with the program given by 'prog' (which defaults to 'twopi'),reading the Postscript output and returning it as a string is the operation is successful. On failure None is returned. There's also the preferred possibility of using: create_'format'(prog='program') which are automatically defined for all the supported formats. [create_ps(),create_gif(),create_dia(),...] If 'prog' is a list instead of a string the fist item is expected to be the program name,followed by any optional command-line arguments for it: ['twopi','-Tdot','-s10'] """ 到您选择的文件中。但是,write 类还提供了 Dot 类方法,这些方法写入指定文件而不是写入临时文件,然后再读回,因此您可以更简单地调用 write

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。