Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 851
Dims Avatar asked Jul 19 '17 19:07

Dims


People also ask

How do I save my keras model?

There are two formats you can use to save an entire model to disk: the TensorFlow SavedModel format, and the older Keras H5 format. The recommended format is SavedModel. It is the default when you use model.save() .

How do I save the keras model in TensorFlow?

Using save_weights() method Now you can simply save the weights of all the layers using the save_weights() method. It saves the weights of the layers contained in the model. It is advised to use the save() method to save h5 models instead of save_weights() method for saving a model using tensorflow.

How do I save keras model in pickle?

USE get_weights AND set_weights TO SAVE AND LOAD MODEL, RESPECTIVELY.


2 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()
like image 67
James Meakin Avatar answered Oct 11 '22 06:10

James Meakin


Here you have another option:

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

    model.summary(print_fn=lambda x: f.write(x + '\n'))
like image 25
sparklingdew Avatar answered Oct 11 '22 05:10

sparklingdew