keras-team/keras · error · ValueError
Weight count mismatch for layer #{k} (named {layer.name} in
Error message
Weight count mismatch for layer #{k} (named {layer.name} in the current model, {name} in the save file). Layer expects {len(symbolic_weights)} weight(s). Received {len(weight_values)} saved weight(s) What it means
After matching layer #k between file and model, load_weights_from_hdf5_group compares the number of weight tensors in the saved layer group against the layer's symbolic weights. A per-layer count mismatch raises this ValueError naming both the current and saved layer names.
Source
Thrown at keras/src/legacy/saving/legacy_h5_format.py:387
layer_group, "weight_names"
)
if weight_names:
filtered_layer_names.append(name)
layer_names = filtered_layer_names
if len(layer_names) != len(filtered_layers):
raise ValueError(
"Layer count mismatch when loading weights from file. "
f"Model expected {len(filtered_layers)} layers, found "
f"{len(layer_names)} saved layers."
)
for k, name in enumerate(layer_names):
layer_group = safe_get_h5_group(group, name)
layer = filtered_layers[k]
symbolic_weights = _legacy_weights(layer)
weight_values = load_subset_weights_from_hdf5_group(layer_group)
if len(weight_values) != len(symbolic_weights):
raise ValueError(
f"Weight count mismatch for layer #{k} (named {layer.name} in "
f"the current model, {name} in the save file). "
f"Layer expects {len(symbolic_weights)} weight(s). Received "
f"{len(weight_values)} saved weight(s)"
)
_set_weights(
layer,
symbolic_weights,
weight_values,
skip_mismatch=skip_mismatch,
name=f"layer #{k} (named {layer.name})",
)
if "top_level_model_weights" in group:
symbolic_weights = list(
# model.weights
v
for v in model._trainable_variables + model._non_trainable_variablesView on GitHub (pinned to 7a34a03db6)
Solutions
- Align the layer definition with the checkpoint (same use_bias, units, etc.)
- Ensure the model is built (call build(input_shape) or run a forward pass) before load_weights
- Use by_name=True so only matching layers are loaded and inspect the mismatched layer named in the message
Example fix
# before
dense = layers.Dense(64, use_bias=False) # saved with use_bias=True
model.load_weights('w.h5')
# after
dense = layers.Dense(64, use_bias=True)
model.load_weights('w.h5') Defensive patterns
Strategy: validation
Validate before calling
model.build(input_shape) # ensure symbolic weights exist before loading
Try / catch
try:
model.load_weights(p)
except ValueError as e:
if 'Weight count mismatch' not in str(e):
raise
model.load_weights(p, by_name=True) Prevention
- Call model.build() before load_weights
- Keep layer hyperparameters (use_bias, units) identical to the checkpoint
When it happens
Trigger: A layer whose weight count changed between save and load: toggling use_bias off, changing units, replacing a layer with a similar one that has fewer/more weights (e.g. BatchNormalization vs LayerNormalization), even when overall layer counts match.
Common situations: Fine-tuning setups where layers were rebuilt with different hyperparameters; loading checkpoints across model refactors; loading before model.build so symbolic weights do not exist yet.
Related errors
- Layer count mismatch when loading weights from file. Model e
- You called `set_weights(weights)` on layer '{self.name}' wit
- Layer '{self.name}' expected {len(all_vars)} variables, but
- `load_model()` using h5 format requires h5py. Could not impo
- No model config found in the file at {filepath}.
AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25).
Data as JSON: /api/errors/d60553954b84776b.
Report an issue: GitHub.