close

How do I get the weights of a layer in Keras?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do I get the weights of a layer in Keras? in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How do I get the weights of a layer in Keras?

  1. How do I get the weights of a layer in Keras?

    Then dense1 is not a layer, it's the output of a layer. The layer is Dense(10, activation='relu')

  2. get the weights of a layer in Keras

    Then dense1 is not a layer, it's the output of a layer. The layer is Dense(10, activation='relu')

Method 1

If you write:

dense1 = Dense(10, activation='relu')(input_x)

Then dense1 is not a layer, it’s the output of a layer. The layer is Dense(10, activation='relu')

So it seems you meant:

dense1 = Dense(10, activation='relu')
y = dense1(input_x)

Here is a full snippet:

import tensorflow as tf
from tensorflow.contrib.keras import layers

input_x = tf.placeholder(tf.float32, [None, 10], name='input_x')    
dense1 = layers.Dense(10, activation='relu')
y = dense1(input_x)

weights = dense1.get_weights()

Method 2

If you want to get weights and biases of all layers, you can simply use:

for layer in model.layers: print(layer.get_config(), layer.get_weights())

This will print all information that’s relevant.

If you want the weights directly returned as numpy arrays, you can use:

first_layer_weights = model.layers[0].get_weights()[0]
first_layer_biases  = model.layers[0].get_weights()[1]
second_layer_weights = model.layers[1].get_weights()[0]
second_layer_biases  = model.layers[1].get_weights()[1]

etc.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read