user673592
user673592

Reputation: 2120

Keras: find out the number of layers

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.

Upvotes: 26

Views: 22499

Answers (3)

Value_Investor
Value_Investor

Reputation: 175

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

Upvotes: 1

vk3who
vk3who

Reputation: 389

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

Upvotes: 0

Maxim
Maxim

Reputation: 53768

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

Upvotes: 47

Related Questions