How to get shapes of all the layers in a model?


Consider the following model

def create_model():
  bias_initializer = tf.keras.initializers.HeNormal()
  model = Sequential()
  model.add(Conv2D(64, (5, 5),  input_shape=(28,28,1),activation="relu", name='conv2d_1', use_bias=True,bias_initializer=bias_initializer))
  model.add(MaxPooling2D(pool_size=(2, 2)))
  model.add(Conv2D(32, (5, 5), activation="relu",name='conv2d_2',  use_bias=True,bias_initializer=bias_initializer))
  model.add(MaxPooling2D(pool_size=(2, 2)))
  model.add(Dense(120, name='dense_1',activation="relu", use_bias=True,bias_initializer=bias_initializer),)
  model.add(Dense(10, name='dense_2', activation="softmax", use_bias=True,bias_initializer=bias_initializer),)

Is there any way I can get the shape/size/dimensions of the all the layer(s) of a model ?
For example in the above model, ‘conv2d_1’ has shape of (64,1,5,5) while ‘conv2d_2’ has shape of (32,64,5,5)?


You can use model.summary(). Or you can loop through all layers and print the output shape:

for layer in model.layers:
    print(f'{}  {layer.output_shape}')

Answered By – AndrzejO

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published