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

Dim*_*ims 16 python stdout keras

Keras中model.summary()方法.它将表打印到stdout.是否可以将其保存到文件中?

小智 24

如果您想要格式化摘要,您可以将print函数传递model.summary()给文件并以这种方式输出到文件:

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

model.summary(print_fn=myprint)
Run Code Online (Sandbox Code Playgroud)

或者,您可以将其序列化为json或yaml字符串,model.to_json()或者model.to_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()
Run Code Online (Sandbox Code Playgroud)

  • model.to_json() 看起来更适合将来检索信息,一旦它是半结构化数据 (2认同)

小智 5

在这里你有另一个选择:

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

    model.summary(print_fn=lambda x: f.write(x + '\n'))
Run Code Online (Sandbox Code Playgroud)