For a Feedforward Network (FFN), it is easy to compute the number of parameters. Given a CNN, LSTM etc is there a quick way to find the number of parameters in a keras model?
Asked
Active
Viewed 3.8k times
4 Answers
137
Models and layers have special method for that purpose:
model.count_params()
Also, to get a short summary of each layer dimensions and parameters, you might find useful the following method
model.summary()

Serj Zaharchenko
- 2,621
- 1
- 17
- 20
-
Notice, that is the count for total, trainable and non-trainable parameters. – trinity420 Apr 13 '22 at 11:43
15
import keras.backend as K
def size(model): # Compute number of params in a model (the actual number of floats)
return sum([np.prod(K.get_value(w).shape) for w in model.trainable_weights])

Anuj Gupta
- 6,328
- 7
- 36
- 55
5
Tracing back the print_summary()
function, Keras developers compute the number of trainable and non_trainable parameters of a given model
as follows:
import keras.backend as K
import numpy as np
trainable_count = int(np.sum([K.count_params(p) for p in set(model.trainable_weights)]))
non_trainable_count = int(np.sum([K.count_params(p) for p in set(model.non_trainable_weights)]))
Given that K.count_params()
is defined as np.prod(int_shape(x))
, this solution is quite similar to the one of Anuj Gupta, except for the use of set()
and the way the shape of the tensors are retrieved.

Miguel A. Sanchez-Perez
- 443
- 1
- 7
- 13
0
After creating your network add: model.summary
And it will give you a summary of your network and the number of parameters.

Eaton
- 11
- 2