tensorflow/models · error · ValueError
The labels and logits must be at least rank 2.
Error message
The labels and logits must be at least rank 2.
What it means
Error "The labels and logits must be at least rank 2." thrown in tensorflow/models.
Source
Thrown at official/projects/volumetric_models/losses/segmentation_losses.py:66
"""
self._dice_score = 0
self._metric_type = metric_type
self._axis = axis
def __call__(self, logits: tf.Tensor, labels: tf.Tensor) -> tf.Tensor:
"""Computes and returns a loss based on 1 - dice score.
Args:
logits: A Tensor of the prediction.
labels: A Tensor of the groundtruth label.
Returns:
The loss value of (1 - dice score).
"""
labels = tf.cast(labels, logits.dtype)
if labels.get_shape().ndims < 2 or logits.get_shape().ndims < 2:
raise ValueError('The labels and logits must be at least rank 2.')
epsilon = tf_keras.backend.epsilon()
keep_label_axis = list(range(len(logits.shape) - 1))
keep_batch_axis = list(range(1, len(logits.shape)))
# Compute sample mask to filter out samples with both all-0's labels and
# predictions because such samples should not contribute to mean dice score
# in this batch.
sample_mask = tf.logical_or(
tf.cast(tf.reduce_sum(labels, axis=keep_batch_axis), dtype=tf.bool),
tf.cast(tf.reduce_sum(logits, axis=keep_batch_axis), dtype=tf.bool))
labels = tf.boolean_mask(labels, sample_mask)
logits = tf.boolean_mask(logits, sample_mask)
# If all samples are filtered out, return 0 as the loss so this batch does
# not contribute.
if labels.shape[0] == 0:
return tf.convert_to_tensor(0.0)View on GitHub (pinned to e006f5f0d5)
When it happens
Trigger: Thrown at official/projects/volumetric_models/losses/segmentation_losses.py:66 when the library encounters an invalid state.
Common situations: See trigger scenarios.
AI-assisted analysis of tensorflow/models@e006f5f0d5 (2026-08-24).
Data as JSON: /api/errors/140872aeee0efe0f.
Report an issue: GitHub.