pythontensorflowkerastf.kerastensorflow-federated

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


Consider the following model

def create_model():
  x_1=tf.Variable(24)
  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(Flatten())
  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)?


Solution

  • 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.name}  {layer.output_shape}')