Python 如何将model.summary()保存到Keras中的文件?

Python 如何将model.summary()保存到Keras中的文件?,python,keras,stdout,Python,Keras,Stdout,在凯拉斯有很多。它将表格打印到标准输出。是否可以将其保存到文件中?如果您想要设置摘要的格式,您可以将打印函数传递到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()将其序列化

在凯拉斯有很多。它将表格打印到标准输出。是否可以将其保存到文件中?

如果您想要设置摘要的格式,您可以将
打印
函数传递到
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字符串,这些字符串可以稍后导入

编辑 在Python3.4+中实现这一点的一种更具Python风格的方法是使用
contextlib.redirect\u stdout

from contextlib import redirect_stdout

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

这里您还有另一个选择:

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

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

使用
redirect\u stdout
的优点是,它适用于在stdout上生成输出的任何东西,因此库开发人员无需像在Keras中所做的那样添加
print\u fn
选项。