keras-team/keras · error · ValueError

You tried to call `count_params` on layer '{self.name}', but

Error message

You tried to call `count_params` on layer '{self.name}', but the layer isn't built. You can build it manually via: `layer.build(input_shape)`.

What it means

count_params() sums the sizes of the layer's weight variables, so it requires the layer to be built. On an unbuilt layer there are no variables and the count is meaningless, hence the error with instructions to build manually.

Source

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

    def add_metric(self, *args, **kwargs):
        # Permanently disabled
        raise NotImplementedError(
            "Layer `add_metric()` method is deprecated. "
            "Add your metric in `Model.compile(metrics=[...])`, "
            "or create metric trackers in init() or build() "
            "when subclassing the layer or model, then call "
            "`metric.update_state()` whenever necessary."
        )

    def count_params(self):
        """Count the total number of scalars composing the weights.

        Returns:
            An integer count.
        """
        if not self.built:
            raise ValueError(
                "You tried to call `count_params` "
                f"on layer '{self.name}', "
                "but the layer isn't built. "
                "You can build it manually via: "
                f"`layer.build(input_shape)`."
            )
        return summary_utils.count_params(self.weights)

    def _maybe_build(self, call_spec):
        if self.built:
            return

        shapes_dict = get_shapes_dict(call_spec)
        first_shape = next(iter(shapes_dict.values()), None)

        # If the layer has a build method, call it with our input shapes.
        if not utils.is_default(self.build):
            shapes_dict = update_shapes_dict_for_target_fn(

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Build the model first: model.build(input_shape) or pass a dummy batch model(np.zeros((1, *shape)))
  2. For Sequential, pass input_shape to the first layer or call build before count_params

Example fix

# before
model = keras.Sequential([keras.layers.Dense(10)])
n = model.count_params()
# after
model.build((None, 32))
n = model.count_params()
Defensive patterns

Strategy: validation

Validate before calling

if not model.built:
    model.build((None, *input_shape))
n = model.count_params()

Type guard

def can_count(model):
    return all(l.built for l in model.layers) if hasattr(model, 'layers') else bool(model.built)

Prevention

When it happens

Trigger: Calling layer.count_params() or model.count_params() on a model whose layers have not processed input (lazy build not triggered); printing model summaries without building first.

Common situations: Reporting parameter counts right after model construction; Keras 3 models no longer build at __init__ even with an input_shape argument in many cases.

Related errors


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