{"record":{"id":"abbcb50d3a06c4da","repo":"keras-team/keras","slug":"r2score-expects-2d-inputs-with-shape-batch-size-abbcb5","errorCode":null,"errorMessage":"R2Score expects 2D inputs with shape (batch_size, output_dim), with output_dim fully defined (not None). Received input shapes: y_pred.shape={y_pred_shape} and y_true.shape={y_true_shape}.","messagePattern":"R2Score expects 2D inputs with shape \\(batch_size, output_dim\\), with output_dim fully defined \\(not None\\)\\. Received input shapes: y_pred\\.shape=(.+?) and y_true\\.shape=(.+?)\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"keras/src/metrics/regression_metrics.py","lineNumber":450,"sourceCode":"        self.class_aggregation = class_aggregation\n        self.num_regressors = num_regressors\n        self.num_samples = self.add_variable(\n            shape=(),\n            initializer=initializers.Zeros(),\n            name=\"num_samples\",\n        )\n        self._built = False\n\n    def _build(self, y_true_shape, y_pred_shape):\n        if len(y_pred_shape) != 2 or len(y_true_shape) != 2:\n            raise ValueError(\n                \"R2Score expects 2D inputs with shape \"\n                \"(batch_size, output_dim). Received input \"\n                f\"shapes: y_pred.shape={y_pred_shape} and \"\n                f\"y_true.shape={y_true_shape}.\"\n            )\n        if y_pred_shape[-1] is None or y_true_shape[-1] is None:\n            raise ValueError(\n                \"R2Score expects 2D inputs with shape \"\n                \"(batch_size, output_dim), with output_dim fully \"\n                \"defined (not None). Received input \"\n                f\"shapes: y_pred.shape={y_pred_shape} and \"\n                f\"y_true.shape={y_true_shape}.\"\n            )\n        num_classes = y_pred_shape[-1]\n        self.squared_sum = self.add_variable(\n            name=\"squared_sum\",\n            shape=[num_classes],\n            initializer=initializers.Zeros(),\n        )\n        self.sum = self.add_variable(\n            name=\"sum\",\n            shape=[num_classes],\n            initializer=initializers.Zeros(),\n        )\n        self.total_mse = self.add_variable(","sourceCodeStart":432,"sourceCodeEnd":468,"githubUrl":"https://github.com/keras-team/keras/blob/7a34a03db60bf60042242d6a556fc3be119046a5/keras/src/metrics/regression_metrics.py#L432-L468","documentation":"Even with rank-2 inputs, R2Score needs output_dim (the last axis) statically known so it can create per-output state variables. If y_pred.shape[-1] or y_true.shape[-1] is None (a dynamic dimension), _build() raises this ValueError. This happens with symbolic KerasTensors whose feature dimension is undefined.","triggerScenarios":"Passing tensors built from keras.Input(shape=(None,)) or layer outputs with an undefined feature dimension to R2Score, e.g. inside a Functional model compiled with metrics=[R2Score()].","commonSituations":"Time-series or variable-length inputs where keras.Input(shape=(None,)) is used; models built with dynamic axes on the feature dimension.","solutions":["Give the input a fully defined feature dimension: keras.Input(shape=(output_dim,)) or fix the producing layer to emit a known last axis.","If output_dim genuinely varies, compute per-batch R-squared outside Keras metrics.","For variable-length sequences, mask or pool to a fixed output_dim before the metric."],"exampleFix":"# before\ninputs = keras.Input(shape=(None,))  # undefined feature dim\nmodel.compile(metrics=[keras.metrics.R2Score()])\n\n# after\ninputs = keras.Input(shape=(window_size,))\nmodel.compile(metrics=[keras.metrics.R2Score()])","handlingStrategy":"validation","validationCode":"assert y_pred.shape[-1] is not None and y_true.shape[-1] is not None, 'output_dim must be statically defined for R2Score'","typeGuard":"def has_static_output_dim(shape) -> bool:\n    return shape[-1] is not None","tryCatchPattern":null,"preventionTips":["Define keras.Input with a concrete feature dimension.","Print model.output_shape before attaching R2Score."],"tags":["keras","metrics","r2-score","dynamic-shape","shape-mismatch"],"backgroundTag":"undefined-tensor-dimension","analyzedSha":"7a34a03db60bf60042242d6a556fc3be119046a5","analyzedAt":"2026-08-25T21:25:25.994Z","schemaVersion":2},"datasetVersion":"2026-08-26T02:17:13.382Z"}