How to save model.summary() to file in Keras?

Question:

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

Asked By: Dims

||

Answers:

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

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.

Edit

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

from contextlib import redirect_stdout

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

Here you have another option:

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

    model.summary(print_fn=lambda x: f.write(x + 'n'))
Answered By: sparklingdew
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.