Keras: How to get layer index when already know layer name?

I already knew the name of a layer of a model, now I want to know that layer's index. Is there any available function to do that? Thank you all.

Upvotes: 10

Views: 11291

Answers (4)

lovetl2002
lovetl2002

Reputation: 1066

One line solution: model.layers.index(model.get_layer(layer_name))

Upvotes: 0

Jamie
Jamie

Reputation: 91

An easy way of doing that is as follows:

layer_names = [layer.name for layer in model.layers]
layer_idx = layer_names.index(your_layer_name)

If you are doing visualization in keras, you can also achieve that as follows:

from vis.utils import utils
layer_idx = utils.find_layer_idx(model, your_layer_name)

Upvotes: 3

maniac
maniac

Reputation: 1192

The answer of Akhilesh as function:

def getLayerIndexByName(model, layername):
    for idx, layer in enumerate(model.layers):
        if layer.name == layername:
            return idx

Upvotes: 5

Akhilesh
Akhilesh

Reputation: 1034

Suppose your model is model and the layerName is name of the layer.

index = None
for idx, layer in enumerate(model.layers):
    if layer.name == layerName:
        index = idx
        break

Here index is the idx of required name.

Upvotes: 8

Related Questions