{"record":{"id":"4e1432392e2f9f47","repo":"keras-team/keras","slug":"r2score-expects-2d-inputs-with-shape-batch-size","errorCode":null,"errorMessage":"R2Score expects 2D inputs with shape (batch_size, output_dim). 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\\)\\. 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":443,"sourceCode":"            )\n        if num_regressors < 0:\n            raise ValueError(\n                \"Invalid value for argument `num_regressors`. \"\n                \"Expected a value >= 0. \"\n                f\"Received: num_regressors={num_regressors}\"\n            )\n        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(),","sourceCodeStart":425,"sourceCodeEnd":461,"githubUrl":"https://github.com/keras-team/keras/blob/7a34a03db60bf60042242d6a556fc3be119046a5/keras/src/metrics/regression_metrics.py#L425-L461","documentation":"R2Score._build(), called from the first update_state, requires both y_true and y_pred to be rank-2 tensors of shape (batch_size, output_dim). If either input is rank 1 (shape (batch,)) the metric raises this ValueError before creating state variables.","triggerScenarios":"metric.update_state(y_true, y_pred) where y_true or y_pred has rank 1 - common with single-output regression models that emit shape (batch,).","commonSituations":"A Dense(1) model whose output was squeezed, targets stored as flat arrays, or custom heads that reshape outputs to rank 1.","solutions":["Expand dims on both inputs: keras.ops.expand_dims(t, -1) so shapes become (batch, 1).","Fix the model to output shape (batch, 1) instead of (batch,).","Store y_true with an explicit trailing output dimension."],"exampleFix":"# before\nr2.update_state(y_true, y_pred)  # both shape (batch,)\n\n# after\nr2.update_state(keras.ops.expand_dims(y_true, -1),\n                keras.ops.expand_dims(y_pred, -1))  # (batch, 1)","handlingStrategy":"type-guard","validationCode":"import keras.ops as ops\ndef ensure2d(t):\n    return ops.expand_dims(t, -1) if len(t.shape) == 1 else t\ny_true, y_pred = ensure2d(y_true), ensure2d(y_pred)","typeGuard":"def is_rank2(x) -> bool:\n    return len(getattr(x, 'shape', ())) == 2","tryCatchPattern":null,"preventionTips":["Design regression targets and outputs with an explicit trailing output_dim axis.","Never squeeze the last dimension of regression outputs."],"tags":["keras","metrics","r2-score","shape-mismatch","rank"],"backgroundTag":"tensor-rank-mismatch","analyzedSha":"7a34a03db60bf60042242d6a556fc3be119046a5","analyzedAt":"2026-08-25T21:25:25.994Z","schemaVersion":2},"datasetVersion":"2026-08-26T02:17:13.382Z"}