27

Is there a way to get the number of layers (not parameters) in a Keras model?

model.summary() is very informative, but it is not straightforward to get the number of layers from it.

Maxim
  • 52,561
  • 27
  • 155
  • 209
user673592
  • 2,090
  • 1
  • 22
  • 37

3 Answers3

46

model.layers will give you the list of all layers. The number is consequently len(model.layers)

Maxim
  • 52,561
  • 27
  • 155
  • 209
  • 2
    `len(model.layers)` fails to count "sublayers", that is layers that exist within a model that's acting as a layer in your ubermodel. – Nickolas Apr 30 '20 at 00:47
0

To get a graphical view of the layer you can use: from keras.utils.vis_utils import plot_model plot_model(model, to_file='layers_plot.png', show_shapes=True, show_layer_names=True)

You will need to pip install pydot and down load and install graphviz from https://graphviz.gitlab.io/download/ Attached is a sample output image

vk3who
  • 349
  • 2
  • 7
0

Although it has been a couple of years since this question was asked, today I ran into the same requirement. As @Nickolas mentioned, the given answers do not account for submodels. Here is a recursive function to find the total number of layers in a model, including submodels:

def count_layers(model):
   num_layers = len(model.layers)
   for layer in model.layers:
      if isinstance(layer, tf.keras.Model):
         num_layers += count_layers(layer)
   return num_layers