gpt4 book ai didi

How to save model.summary() to file in Keras?(如何在KERAS中将Model.sum()保存到文件中?)

转载 作者:bug小助手 更新时间:2023-10-25 14:22:14 30 4
gpt4 key购买 nike



There is model.summary() method in Keras. It prints table to stdout. Is it possible to save this to file?

在KERAS中有mod.sum()方法。它将表打印到标准输出。可以将此文件保存到文件中吗?


更多回答
优秀答案推荐

If you want the formatting of summary you can pass a print function to model.summary() and output to file that way:

如果您想要摘要的格式,您可以将打印函数传递给Model.sum(),并以这种方式输出到文件:


def myprint(s):
with open('modelsummary.txt','a') as f:
print(s, file=f)

model.summary(print_fn=myprint)

Alternatively, you can serialize it to a json or yaml string with model.to_json() or model.to_yaml() which can be imported back later.

或者,您也可以将其序列化为一个json或YAML字符串,该字符串可以使用Model.to_json()或Model.to_YAML()在以后导入回来。


Edit


An more pythonic way to do this in Python 3.4+ is to use contextlib.redirect_stdout

在Python3.4+中执行此操作的一种更具蟒蛇风格的方法是使用Conextlib.reDirect_stdout


from contextlib import redirect_stdout

with open('modelsummary.txt', 'w') as f:
with redirect_stdout(f):
model.summary()


Here you have another option:

在这里,您有另一个选择:


with open('modelsummary.txt', 'w') as f:

model.summary(print_fn=lambda x: f.write(x + '\n'))


This seems to be more succinct and pythonic:

这句话似乎更简洁、更有戏剧性:


with open('model.summary', 'w') as sys.stdout:
model.summary()

# ...reset 'sys.stdout' for later script output
sys.stdout = sys.__stdout__

更多回答

model.to_json() looks like better to retrieve information in the future, once that is a semi-structured data

如果信息是半结构化数据,那么在将来检索信息时,mod.to_json()看起来更好

'w+' should be replaced with 'a', because model.summary writes several times.

应该将‘w+’替换为‘a’,因为Model.sum会多次写入。

This is neat and utterly Pythonic.

这是干净利落的,完全是毕德式的。

The advantage of using redirect_stdout is that it works for anything that produces output on stdout, so no need for library developers to add print_fn options as has been done here in Keras.

使用reDirect_stdout的优点是,它适用于在stdout上生成输出的任何东西,因此库开发人员不需要像在Kera中那样添加print_fn选项。

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com