Transfer weights in memory
Initialize one compatible model or layer with another's learned parameters.
Keras · Module
Model.set_weights assigns a layer or model's weights from a list of NumPy arrays. The arrays must match the target's weight count, shapes, and creation order.
Call the model or layer first so its weights exist, then pass a list of NumPy arrays to set_weights. Keras assigns those arrays according to the order in which the layer created its weights; the list length and every array shape must match the target layer's current weight specification.
Model.set_weights(weights)| Name | Type | Description |
|---|---|---|
weights | list of NumPy arrays | A list of NumPy arrays whose count and shapes match the target layer's weights. |
None
import numpy as np
import keras
source = keras.Sequential([keras.layers.Dense(2)])
target = keras.Sequential([keras.layers.Dense(2)])
source(np.zeros((1, 3)))
target(np.zeros((1, 3)))
target.set_weights(source.get_weights())Build both layers before transferring the source layer's NumPy weight arrays to the target.
Initialize one compatible model or layer with another's learned parameters.
Restore or apply explicitly prepared NumPy weight values to a built object.
Validate that two compatible objects share the same weight structure before copying parameters.
set_weights accepts a list of NumPy arrays and assigns them to the layer's weights. The arrays must be ordered the same way the layer created its weights.
Follow-up: What happens if the list is incompatible? Keras raises ValueError when its number of arrays or shapes do not match the layer specification.
The target layer must already have instantiated weights, typically by calling or building it. The input list must match the target's weight structure and shapes.
Follow-up: Why can two apparently similar models fail to exchange weights? Their weight creation order, count, or shapes can differ, so the list no longer matches the target specification.
A common transfer pattern is target.set_weights(source.get_weights()). get_weights produces NumPy arrays, and set_weights consumes them in the corresponding weight order.
Follow-up: How would you diagnose a ValueError? Compare the source arrays' count and shapes with the target layer's get_weights output and verify both objects are built.
Model.get_weights()Layer.get_weights()Layer.set_weights()Model.save_weights()Model.load_weights()