tensorflow/models · error · RuntimeError
Weighted sparse categorical crossentropy expects `labels` to
Error message
Weighted sparse categorical crossentropy expects `labels` to have a rank of one less than `predictions`. labels.shape was %s, and predictions.shape was %s.
What it means
Error "Weighted sparse categorical crossentropy expects `labels` to have a rank of one less than `predictions`. labels.shape was %s, and predictions.shape was %s." thrown in tensorflow/models.
Source
Thrown at official/nlp/modeling/losses/weighted_sparse_categorical_crossentropy.py:35
import tensorflow as tf, tf_keras
def _adjust_labels(labels, predictions):
"""Adjust the 'labels' tensor by squeezing it if needed."""
labels = tf.cast(labels, tf.int32)
if len(predictions.shape) == len(labels.shape):
labels = tf.squeeze(labels, [-1])
return labels, predictions
def _validate_rank(labels, predictions, weights):
if weights is not None and len(weights.shape) != len(labels.shape):
raise RuntimeError(
("Weight and label tensors were not of the same rank. weights.shape "
"was %s, and labels.shape was %s.") %
(predictions.shape, labels.shape))
if (len(predictions.shape) - 1) != len(labels.shape):
raise RuntimeError(
("Weighted sparse categorical crossentropy expects `labels` to have a "
"rank of one less than `predictions`. labels.shape was %s, and "
"predictions.shape was %s.") % (labels.shape, predictions.shape))
def loss(labels, predictions, weights=None, from_logits=False):
"""Calculate a per-batch sparse categorical crossentropy loss.
This loss function assumes that the predictions are post-softmax.
Args:
labels: The labels to evaluate against. Should be a set of integer indices
ranging from 0 to (vocab_size-1).
predictions: The network predictions. Should have softmax already applied.
weights: An optional weight array of the same shape as the 'labels' array.
If None, all examples will be used.
from_logits: Whether the input predictions are logits.
Returns:View on GitHub (pinned to e006f5f0d5)
When it happens
Trigger: Thrown at official/nlp/modeling/losses/weighted_sparse_categorical_crossentropy.py:35 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/67c981c82a427bbe.
Report an issue: GitHub.