{"record":{"id":"16c5a75b9986dd1a","repo":"keras-team/keras","slug":"you-tried-to-call-count-params-on-layer-self-n","errorCode":null,"errorMessage":"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)`.","messagePattern":"You tried to call `count_params` on layer '(.+?)', but the layer isn't built\\. You can build it manually via: `layer\\.build\\(input_shape\\)`\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"keras/src/layers/layer.py","lineNumber":1555,"sourceCode":"\n    def add_metric(self, *args, **kwargs):\n        # Permanently disabled\n        raise NotImplementedError(\n            \"Layer `add_metric()` method is deprecated. \"\n            \"Add your metric in `Model.compile(metrics=[...])`, \"\n            \"or create metric trackers in init() or build() \"\n            \"when subclassing the layer or model, then call \"\n            \"`metric.update_state()` whenever necessary.\"\n        )\n\n    def count_params(self):\n        \"\"\"Count the total number of scalars composing the weights.\n\n        Returns:\n            An integer count.\n        \"\"\"\n        if not self.built:\n            raise ValueError(\n                \"You tried to call `count_params` \"\n                f\"on layer '{self.name}', \"\n                \"but the layer isn't built. \"\n                \"You can build it manually via: \"\n                f\"`layer.build(input_shape)`.\"\n            )\n        return summary_utils.count_params(self.weights)\n\n    def _maybe_build(self, call_spec):\n        if self.built:\n            return\n\n        shapes_dict = get_shapes_dict(call_spec)\n        first_shape = next(iter(shapes_dict.values()), None)\n\n        # If the layer has a build method, call it with our input shapes.\n        if not utils.is_default(self.build):\n            shapes_dict = update_shapes_dict_for_target_fn(","sourceCodeStart":1537,"sourceCodeEnd":1573,"githubUrl":"https://github.com/keras-team/keras/blob/7a34a03db60bf60042242d6a556fc3be119046a5/keras/src/layers/layer.py#L1537-L1573","documentation":"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.","triggerScenarios":"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.","commonSituations":"Reporting parameter counts right after model construction; Keras 3 models no longer build at __init__ even with an input_shape argument in many cases.","solutions":["Build the model first: model.build(input_shape) or pass a dummy batch model(np.zeros((1, *shape)))","For Sequential, pass input_shape to the first layer or call build before count_params"],"exampleFix":"# before\nmodel = keras.Sequential([keras.layers.Dense(10)])\nn = model.count_params()\n# after\nmodel.build((None, 32))\nn = model.count_params()","handlingStrategy":"validation","validationCode":"if not model.built:\n    model.build((None, *input_shape))\nn = model.count_params()","typeGuard":"def can_count(model):\n    return all(l.built for l in model.layers) if hasattr(model, 'layers') else bool(model.built)","tryCatchPattern":null,"preventionTips":["Build models with dummy data before summarizing or counting","Pass input_shape to Sequential first layers or call build() explicitly"],"tags":["keras","build","parameter-count"],"backgroundTag":"layer-not-built","analyzedSha":"7a34a03db60bf60042242d6a556fc3be119046a5","analyzedAt":"2026-08-25T21:25:25.994Z","schemaVersion":2},"datasetVersion":"2026-08-26T02:17:13.382Z"}