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),)
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.
CodePudding user response:
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([i.name.split('/')[0] for i in model.trainable_weights])
>>>
array(['conv2d_1', 'conv2d_2', 'dense_1', 'dense_2'], dtype='<U8')
len(np.unique([i.name.split('/')[0] for i in model.trainable_weights]))
>>>
4