keras-team/keras · error · ValueError

Layer count mismatch when loading weights from file. Model e

Error message

Layer count mismatch when loading weights from file. Model expected {len(filtered_layers)} layers, found {len(layer_names)} saved layers.

What it means

load_weights_from_hdf5_group matches saved layer groups to the model's layers that have weights. After filtering both sides to weight-bearing layers, a count mismatch raises this ValueError: the file and the model disagree on how many weight-bearing layers exist.

Source

Thrown at keras/src/legacy/saving/legacy_h5_format.py:375

    filtered_layers = []
    for layer in model.layers:
        weights = _legacy_weights(layer)
        if weights:
            filtered_layers.append(layer)

    layer_names = load_attributes_from_hdf5_group(group, "layer_names")
    filtered_layer_names = []
    for name in layer_names:
        layer_group = safe_get_h5_group(group, name)
        weight_names = load_attributes_from_hdf5_group(
            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(

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Load with by_name=True so layers are matched by name instead of by order
  2. Make the architecture match the checkpoint exactly before load_weights
  3. Re-save the weights from the exact current architecture, or regenerate the checkpoint

Example fix

# before
model.load_weights('old.h5')
# after
model.load_weights('old.h5', by_name=True)
Defensive patterns

Strategy: validation

Validate before calling

file_layers = len([g for g in f['layer_weights'] if 'weight_names' in g.attrs and len(g.attrs['weight_names'])])
model_layers = len([l for l in model.layers if l.weights])
assert file_layers == model_layers, (file_layers, model_layers)

Try / catch

try:
    model.load_weights(p)
except ValueError as e:
    if 'Layer count mismatch' not in str(e):
        raise
    model.load_weights(p, by_name=True)

Prevention

When it happens

Trigger: model.load_weights('w.h5') where the file was saved from a different architecture: layers added/removed, or layers switched between weight-bearing and weightless, loaded with by_name=False onto a mismatched model.

Common situations: Evolving a model architecture between training runs; loading old checkpoints into a refactored model; loading a Sequential checkpoint into a Functional model with extra layers.

Related errors


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