There is model.summary() method in Keras. It prints table to stdout. Is it possible to save this to file?
Asked
Active
Viewed 2.5k times
2 Answers
63
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()

James Meakin
- 865
- 7
- 9
-
2model.to_json() looks like better to retrieve information in the future, once that is a semi-structured data – Jonas Ferreira Jul 26 '21 at 16:33
-
1'w+' should be replaced with 'a', because model.summary writes several times. – Andrey May 20 '22 at 19:46
15
Here you have another option:
with open('modelsummary.txt', 'w') as f:
model.summary(print_fn=lambda x: f.write(x + '\n'))

sparklingdew
- 169
- 1
- 4
-
1
-
1The advantage of using `redirect_stdout` is that it works for anything that produces output on stdout, so no need for library developers to add `print_fn` options as has been done here in Keras. – James Meakin Apr 13 '21 at 14:04