我有一个<IPython.core.display.Image object>格式的文件,我收到的文件如下:
graph = uplift_tree_plot (uplift_model.fitted_uplift_tree, x_names)
img = Image (graph.create_png ())我怎样才能保存这个png图像呢?
发布于 2021-07-08 06:30:55
您似乎在使用causalml生成graph,因此,通过检查uplift_tree_plot()的源代码,我们可以看到它返回了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 graphpydotplus API文档对于理解对象可以做什么也没有多大帮助,所以我们也可以通过检查其来源来理解API提供了什么。这是以一种很难搜索我们所关心的函数的方式编写的,因为它动态地生成一些函数,但是Dot.__init__设置函数以各种格式呈现图像,在调用create_png时委托Dot.create执行实际呈现。该功能至少有一些文档:
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方法,这些方法可以写入指定的文件,而不是写入临时文件,然后将临时文件读取回来,这样您就可以更简单地调用graph.write_png('my_graph.png')。
https://stackoverflow.com/questions/68296393
复制相似问题