Reputation: 51259
There is model.summary() method in Keras. It prints table to stdout. Is it possible to save this to file?
Upvotes: 40
Views: 28765
Reputation: 21
This seems to be more succinct and pythonic:
with open('model.summary', 'w') as sys.stdout:
model.summary()
# ...reset 'sys.stdout' for later script output
sys.stdout = sys.__stdout__
Upvotes: 0
Reputation: 885
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.
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()
Upvotes: 65
Reputation: 179
Here you have another option:
with open('modelsummary.txt', 'w') as f:
model.summary(print_fn=lambda x: f.write(x + '\n'))
Upvotes: 16