{"record":{"id":"140872aeee0efe0f","repo":"tensorflow/models","slug":"the-labels-and-logits-must-be-at-least-rank-2","errorCode":null,"errorMessage":"The labels and logits must be at least rank 2.","messagePattern":"The labels and logits must be at least rank 2\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"official/projects/volumetric_models/losses/segmentation_losses.py","lineNumber":66,"sourceCode":"    \"\"\"\n    self._dice_score = 0\n    self._metric_type = metric_type\n    self._axis = axis\n\n  def __call__(self, logits: tf.Tensor, labels: tf.Tensor) -> tf.Tensor:\n    \"\"\"Computes and returns a loss based on 1 - dice score.\n\n    Args:\n      logits: A Tensor of the prediction.\n      labels: A Tensor of the groundtruth label.\n\n    Returns:\n      The loss value of (1 - dice score).\n    \"\"\"\n    labels = tf.cast(labels, logits.dtype)\n\n    if labels.get_shape().ndims < 2 or logits.get_shape().ndims < 2:\n      raise ValueError('The labels and logits must be at least rank 2.')\n\n    epsilon = tf_keras.backend.epsilon()\n    keep_label_axis = list(range(len(logits.shape) - 1))\n    keep_batch_axis = list(range(1, len(logits.shape)))\n\n    # Compute sample mask to filter out samples with both all-0's labels and\n    # predictions because such samples should not contribute to mean dice score\n    # in this batch.\n    sample_mask = tf.logical_or(\n        tf.cast(tf.reduce_sum(labels, axis=keep_batch_axis), dtype=tf.bool),\n        tf.cast(tf.reduce_sum(logits, axis=keep_batch_axis), dtype=tf.bool))\n    labels = tf.boolean_mask(labels, sample_mask)\n    logits = tf.boolean_mask(logits, sample_mask)\n\n    # If all samples are filtered out, return 0 as the loss so this batch does\n    # not contribute.\n    if labels.shape[0] == 0:\n      return tf.convert_to_tensor(0.0)","sourceCodeStart":48,"sourceCodeEnd":84,"githubUrl":"https://github.com/tensorflow/models/blob/e006f5f0d534913e49c1f1dae87364039fa607e2/official/projects/volumetric_models/losses/segmentation_losses.py#L48-L84","documentation":"Error \"The labels and logits must be at least rank 2.\" thrown in tensorflow/models.","triggerScenarios":"Thrown at official/projects/volumetric_models/losses/segmentation_losses.py:66 when the library encounters an invalid state.","commonSituations":"See trigger scenarios.","solutions":[],"exampleFix":null,"handlingStrategy":null,"validationCode":null,"typeGuard":null,"tryCatchPattern":null,"preventionTips":[],"tags":[],"backgroundTag":null,"analyzedSha":"e006f5f0d534913e49c1f1dae87364039fa607e2","analyzedAt":"2026-08-24T14:09:15.576Z","schemaVersion":2},"datasetVersion":"2026-08-24T17:17:21.512Z"}