Is there any way I can count the number of layers in a model, i.e., numerical answer?


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),)

I can extract summary of the model instance but is there any method that can give/count the number of layers (with trainable parameters)?
For example, the above posted model has 4 layers with trainable parameters.


model.trainable_weights gives a list of all the trainable weights. Weights and biases are considered independently, so you need to take unique count of the total number of weights

np.unique(['/')[0] for i in model.trainable_weights])
array(['conv2d_1', 'conv2d_2', 'dense_1', 'dense_2'], dtype='<U8')

len(np.unique(['/')[0] for i in model.trainable_weights]))

Answered By – Vishal Balaji

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