Discussions>keras get layer of the model>

keras get layer of the model

Guys, I've built a Keras model with Sequential, but I want to get access to every single layer separately. Which is the best and simplest way to get the layer of Keras model?

from keras.models import Sequential
from keras.layers import Dense

model = Sequential()
model.add(Dense(128, input_dim=784, activation='relu'))
model.add(Dense(64, activation='relu'))
model.add(Dense(32, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

This is a simple example of a Sequential model.

2 votesLP215.00
1 Answers
JW270.00
2

If you visualize your Keras model, you will see something like this. It says the name of your model is "sequential_1" and you've got a couple of Dense layers with some trainable parameters.
Every layer of the Keras model has a unique name. e.g. "dense_1", "dense_2" etc.

Model: "sequential_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
dense_1 (Dense)              (None, 128)               100480
_________________________________________________________________
dense_2 (Dense)              (None, 64)                8256
_________________________________________________________________
dense_3 (Dense)              (None, 32)                2080
_________________________________________________________________
dense_4 (Dense)              (None, 1)                 33
=================================================================
Total params: 110,849
Trainable params: 110,849
Non-trainable params: 0
_________________________________________________________________

Keras has a function for getting a layer with this unique name. So you need just to call that function and pass a name for the layer.

layer = model.get_layer('dense_1')

Also, a Keras model's layer has some properties inside of it. Like the input, output, weights, parameters, etc. Take a look at this doc. The are other discussions in this platform about the layers of Keras model.

Reply
Couldn't find what you were looking for?and we will find an expert to answer.
How helpful was this page?