Keras
machine learning
neural networks
deep learning
layer weights

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

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Keras layers expose their parameters directly, so inspecting weights is usually straightforward once the layer has been built. The two things that trip people up most often are choosing the right API and remembering that unbuilt layers do not yet have initialized weight arrays.

The Simplest Way: get_weights()

For a built layer, get_weights() returns a list of NumPy arrays.

python
1import tensorflow as tf
2
3model = tf.keras.Sequential([
4    tf.keras.layers.Input(shape=(4,)),
5    tf.keras.layers.Dense(3, activation="relu", name="hidden"),
6    tf.keras.layers.Dense(1, name="output"),
7])
8
9hidden = model.get_layer("hidden")
10weights = hidden.get_weights()
11
12kernel, bias = weights
13print(kernel.shape)
14print(bias.shape)

For a dense layer, the list usually contains:

  • the kernel matrix
  • the bias vector

The exact shapes depend on the input size and the number of units.

Make Sure the Layer Is Built First

Keras only creates weight variables once the layer knows its input shape. If the layer has not been built yet, get_weights() may return an empty list.

python
1import tensorflow as tf
2
3layer = tf.keras.layers.Dense(3)
4print(layer.get_weights())  # often []
5
6layer.build((None, 4))
7print([w.shape for w in layer.get_weights()])

In a full model, calling the model once or defining an input shape usually builds everything automatically.

Access Tensor Variables Directly

If you want TensorFlow variables instead of NumPy arrays, inspect weights, trainable_weights, or non_trainable_weights.

python
1layer = model.get_layer("hidden")
2
3for variable in layer.weights:
4    print(variable.name, variable.shape)

This is useful when you want to work inside TensorFlow code rather than immediately converting to NumPy.

Modify the Weights

You can also set weights manually, as long as the shapes match exactly.

python
1import numpy as np
2
3layer = model.get_layer("hidden")
4kernel, bias = layer.get_weights()
5
6new_kernel = np.zeros_like(kernel)
7new_bias = np.ones_like(bias)
8
9layer.set_weights([new_kernel, new_bias])
10print(layer.get_weights()[1])

This is useful for experiments, weight transfer, or deterministic initialization during tests.

Access Weights by Index or Name

If you do not name the layer, you can still access it by index:

python
first_dense = model.layers[0]
print(first_dense.get_weights())

But named access is often better in larger models:

python
output_layer = model.get_layer("output")
print(output_layer.get_weights())

Layer names make inspection code more stable when the model architecture changes slightly.

Custom Layers Work the Same Way

If you define your own layer and add weights with add_weight, those variables show up through the same APIs.

python
1class ScaledBias(tf.keras.layers.Layer):
2    def build(self, input_shape):
3        self.scale = self.add_weight(shape=(input_shape[-1],), initializer="ones")
4        self.bias = self.add_weight(shape=(input_shape[-1],), initializer="zeros")
5
6    def call(self, inputs):
7        return inputs * self.scale + self.bias
8
9layer = ScaledBias()
10layer.build((None, 5))
11
12for w in layer.weights:
13    print(w.shape)

So once you understand the standard layer APIs, custom layers follow the same pattern.

Common Pitfalls

The biggest mistake is calling get_weights() before the layer or model has been built. No input shape means no initialized weights yet.

Another issue is assuming every layer has both kernel and bias arrays. Some layers have different parameter structures, and some have no trainable weights at all.

Developers also mix up TensorFlow variables with NumPy arrays. layer.weights returns variables, while layer.get_weights() returns NumPy copies of their values.

Finally, if you use set_weights(...), the shapes must match exactly. Keras will not silently reshape the arrays for you.

Summary

  • Use layer.get_weights() to retrieve a layer's parameter values as NumPy arrays.
  • Make sure the layer is built before expecting weights to exist.
  • Use layer.weights or trainable_weights when you want TensorFlow variables.
  • Named layers are easier to inspect than index-based access in larger models.
  • When setting weights manually, the replacement arrays must match the original shapes exactly.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.