【发布时间】:2017-12-25 05:25:48
【问题描述】:
Keras 中有model.summary() method。它将表格打印到标准输出。是否可以将其保存到文件中?
【问题讨论】:
Keras 中有model.summary() method。它将表格打印到标准输出。是否可以将其保存到文件中?
【问题讨论】:
这里你有另一个选择:
with open('modelsummary.txt', 'w') as f:
model.summary(print_fn=lambda x: f.write(x + '\n'))
【讨论】:
redirect_stdout 的优势在于它适用于任何在标准输出上产生输出的东西,因此库开发人员无需像在 Keras 中所做的那样添加print_fn 选项。
如果您想要摘要的格式,您可以将 print 函数传递给 model.summary() 并以这种方式输出到文件:
def myprint(s):
with open('modelsummary.txt','w+') as f:
print(s, file=f)
model.summary(print_fn=myprint)
或者,您可以使用 model.to_json() 或 model.to_yaml() 将其序列化为 json 或 yaml 字符串,这些字符串可以稍后导入。
在 Python 3.4+ 中执行此操作的更 Pythonic 方式是使用 contextlib.redirect_stdout
from contextlib import redirect_stdout
with open('modelsummary.txt', 'w') as f:
with redirect_stdout(f):
model.summary()
【讨论】: