Keras model.summary() object to string

And if you want to write to a log:

import logging
logger = logging.getLogger(__name__)

model.summary(print_fn=logger.info)

For me, this worked to just get the model summary as a string:

stringlist = []
model.summary(print_fn=lambda x: stringlist.append(x))
short_model_summary = "\n".join(stringlist)
print(short_model_summary)

With my version of Keras (2.0.6) and Python (3.5.0), this works for me:

# Create an empty model
from keras.models import Sequential
model = Sequential()

# Open the file
with open(filename + 'report.txt','w') as fh:
    # Pass the file handle in as a lambda function to make it callable
    model.summary(print_fn=lambda x: fh.write(x + '\n'))

This outputs the following lines to the file:

_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
Total params: 0
Trainable params: 0
Non-trainable params: 0
_________________________________________________________________