keras-team/keras · error · ValueError

You called `set_weights(weights)` on layer '{self.name}' wit

Error message

You called `set_weights(weights)` on layer '{self.name}' with a weight list of length {len(weights)}, but the layer was expecting {len(layer_weights)} weights.

What it means

set_weights() requires the incoming list length to exactly match layer.weights. This error reports the mismatch between the supplied list and the number of variables the layer actually created after being built.

Source

Thrown at keras/src/layers/layer.py:779

        return metrics

    @property
    def metrics_variables(self):
        """List of all metric variables."""
        vars = []
        for metric in self.metrics:
            vars.extend(metric.variables)
        return vars

    def get_weights(self):
        """Return the values of `layer.weights` as a list of NumPy arrays."""
        return [v.numpy() for v in self.weights]

    def set_weights(self, weights):
        """Sets the values of `layer.weights` from a list of NumPy arrays."""
        layer_weights = self.weights
        if len(layer_weights) != len(weights):
            raise ValueError(
                f"You called `set_weights(weights)` on layer '{self.name}' "
                f"with a weight list of length {len(weights)}, but the layer "
                f"was expecting {len(layer_weights)} weights."
            )
        for variable, value in zip(layer_weights, weights):
            if variable.shape != value.shape:
                raise ValueError(
                    f"Layer {self.name} weight shape {variable.shape} "
                    "is not compatible with provided weight "
                    f"shape {value.shape}."
                )
            variable.assign(value)

    @property
    def dtype_policy(self):
        return self._dtype_policy

    @dtype_policy.setter

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Compare len(model.weights) with len(weights) and reconcile the architecture (layer count, units, build shape)
  2. Use model.load_weights(path) with the original checkpoint instead of manually assembling lists
  3. If transferring, extract per-layer weights: get_layer(name).get_weights() and set them per layer

Example fix

# before
model.set_weights(wrong_len_arrays)
# after
assert len(model.weights) == len(arrays), (len(model.weights), len(arrays))
model.set_weights(arrays)
Defensive patterns

Strategy: validation

Validate before calling

weights = [np.asarray(w) for w in weights]
assert len(weights) == len(model.weights), f'{len(weights)} != {len(model.weights)}'

Type guard

def weights_match(model, weights):
    return len(weights) == len(model.weights) and all(
        v.shape == np.shape(w) for v, w in zip(model.weights, weights))

Try / catch

try:
    model.set_weights(weights)
except ValueError as e:
    raise RuntimeError(f'checkpoint/model mismatch: {e}') from e

Prevention

When it happens

Trigger: Calling model.set_weights(np_arrays) where the array count differs from len(layer.weights); loading weights from a model with a different architecture; calling set_weights before the layer is built or after build with a different input shape that changes variable count.

Common situations: Transferring weights between model versions (extra/missing layer); forgetting non-trainable weights (BN moving mean/variance, RNG state) in the list; loading a checkpoint saved from a differently-configured model.

Related errors


AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25). Data as JSON: /api/errors/0c3cdbcbe2ee93ab. Report an issue: GitHub.