【问题标题】:How to save model.summary() to file in Keras?如何将 model.summary() 保存到 Keras 中的文件?
【发布时间】:2017-12-25 05:25:48
【问题描述】:

Keras 中有model.summary() method。它将表格打印到标准输出。是否可以将其保存到文件中?

【问题讨论】:

    标签: python keras stdout


    【解决方案1】:

    这里你有另一个选择:

    with open('modelsummary.txt', 'w') as f:
    
        model.summary(print_fn=lambda x: f.write(x + '\n'))
    

    【讨论】:

    • 这很简洁,完全是 Pythonic。
    • 使用redirect_stdout 的优势在于它适用于任何在标准输出上产生输出的东西,因此库开发人员无需像在 Keras 中所做的那样添加print_fn 选项。
    【解决方案2】:

    如果您想要摘要的格式,您可以将 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()
    

    【讨论】:

    • model.to_json() 看起来更好地在未来检索信息,一旦那是半结构化数据
    猜你喜欢
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多