Keras: How to get layer shapes in a Sequential model

Toke Faurby picture Toke Faurby · May 2, 2017 · Viewed 48.8k times · Source

I would like to access the layer size of all the layers in a Sequential Keras model. My code:

model = Sequential()
model.add(Conv2D(filters=32, 
               kernel_size=(3,3), 
               input_shape=(64,64,3)
        ))
model.add(MaxPooling2D(pool_size=(3,3), strides=(2,2)))

Then I would like some code like the following to work

for layer in model.layers:
    print(layer.get_shape())

.. but it doesn't. I get the error: AttributeError: 'Conv2D' object has no attribute 'get_shape'

Answer

Toke Faurby picture Toke Faurby · May 2, 2017

If you want the output printed in a fancy way:

model.summary()

If you want the sizes in an accessible form

for layer in model.layers:
    print(layer.get_output_at(0).get_shape().as_list())

There are probably better ways to access the shapes than this. Thanks to Daniel for the inspiration.