How to Get Layer Name in Keras

  • Post category:Keras / Python

To get the names of the layers in a Keras model, you can access them through the name attribute of each layer. Here’s how to do it:

Assuming you have a Keras model named model, you can get the layer names like this:

layer_names = [layer.name for layer in model.layers]
print("Layer names:", layer_names)

In this code:

  1. model.layers provides a list of all the layers in the Keras model.
  2. We use a list comprehension to extract the name of each layer using layer.name.
  3. layer_names is a list containing the names of all the layers in the model.

Working Example:

# Import necessary libraries
import keras
from keras.models import Sequential
from keras.layers import Dense

# Create a simple Keras model (for demonstration)
model = Sequential()
model.add(Dense(units=64, activation='relu', input_dim=100))
model.add(Dense(units=10, activation='softmax'))
layer_names = [layer.name for layer in model.layers]
print("Layer names:", layer_names)

Output:

Layer names: ['dense_16', 'dense_17']

When you run this code, it will print the names of all the layers in your Keras model to the console. This is useful for identifying specific layers in your model and for referencing them when needed in your code.