TheAlgorithms/Python · error · ValueError

Batch size of y_true and y_pred must be equal.

Error message

Batch size of y_true and y_pred must be equal.

What it means

Thrown by perplexity_loss when the batch dimension (shape[0]) of y_true and y_pred differ. Perplexity expects y_true as (batch, sentence_length) integer token ids and y_pred as (batch, sentence_length, vocab_size) probabilities; both must share the same number of sentences.

Source

Thrown at machine_learning/loss_functions.py:556

    ...
    ValueError: Label value must not be greater than vocabulary size.
    >>> y_true = np.array([[1, 4]])
    >>> y_pred = np.array(
    ...    [[[0.28, 0.19, 0.21 , 0.15, 0.15],
    ...      [0.24, 0.19, 0.09, 0.18, 0.27]],
    ...      [[0.03, 0.26, 0.21, 0.18, 0.30],
    ...       [0.28, 0.10, 0.33, 0.15, 0.12]]]
    ... )
    >>> perplexity_loss(y_true, y_pred)
    Traceback (most recent call last):
    ...
    ValueError: Batch size of y_true and y_pred must be equal.
    """

    vocab_size = y_pred.shape[2]

    if y_true.shape[0] != y_pred.shape[0]:
        raise ValueError("Batch size of y_true and y_pred must be equal.")
    if y_true.shape[1] != y_pred.shape[1]:
        raise ValueError("Sentence length of y_true and y_pred must be equal.")
    if np.max(y_true) > vocab_size:
        raise ValueError("Label value must not be greater than vocabulary size.")

    # Matrix to select prediction value only for true class
    filter_matrix = np.array(
        [[list(np.eye(vocab_size)[word]) for word in sentence] for sentence in y_true]
    )

    # Getting the matrix containing prediction for only true class
    true_class_pred = np.sum(y_pred * filter_matrix, axis=2).clip(epsilon, 1)

    # Calculating perplexity for each sentence
    perp_losses = np.exp(np.negative(np.mean(np.log(true_class_pred), axis=1)))

    return np.mean(perp_losses)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Slice to a common batch: n = min(len(y_true), len(y_pred)); use y_true[:n], y_pred[:n].
  2. Regenerate y_pred with the exact batch the references were built from.
  3. Verify y_true.shape == y_pred.shape[:2] before the call.

Example fix

# before
loss = perplexity_loss(y_true, y_pred)  # y_true has 2 sentences, y_pred has 3

# after
n = min(y_true.shape[0], y_pred.shape[0])
loss = perplexity_loss(y_true[:n], y_pred[:n])
Defensive patterns

Strategy: validation

Validate before calling

assert y_true.shape[0] == y_pred.shape[0]
assert y_true.shape[1] == y_pred.shape[1]
loss = perplexity_loss(y_true, y_pred)

Type guard

def perplexity_shapes_ok(y_true: np.ndarray, y_pred: np.ndarray) -> bool:
    return (
        y_pred.ndim == 3
        and y_true.ndim == 2
        and y_true.shape == y_pred.shape[:2]
    )

Prevention

When it happens

Trigger: Calling perplexity_loss(y_true, y_pred) where y_true.shape[0] != y_pred.shape[0], e.g. 2 reference sentences against 3 prediction blocks.

Common situations: Reference corpus and model output built from different batch sizes; last partial batch handled inconsistently; extra sample appended during decoding.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/723c11279943829d. Report an issue: GitHub.