{"record":{"id":"723c11279943829d","repo":"TheAlgorithms/Python","slug":"batch-size-of-y-true-and-y-pred-must-be-equal","errorCode":null,"errorMessage":"Batch size of y_true and y_pred must be equal.","messagePattern":"Batch size of y_true and y_pred must be equal\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"machine_learning/loss_functions.py","lineNumber":556,"sourceCode":"    ...\n    ValueError: Label value must not be greater than vocabulary size.\n    >>> y_true = np.array([[1, 4]])\n    >>> y_pred = np.array(\n    ...    [[[0.28, 0.19, 0.21 , 0.15, 0.15],\n    ...      [0.24, 0.19, 0.09, 0.18, 0.27]],\n    ...      [[0.03, 0.26, 0.21, 0.18, 0.30],\n    ...       [0.28, 0.10, 0.33, 0.15, 0.12]]]\n    ... )\n    >>> perplexity_loss(y_true, y_pred)\n    Traceback (most recent call last):\n    ...\n    ValueError: Batch size of y_true and y_pred must be equal.\n    \"\"\"\n\n    vocab_size = y_pred.shape[2]\n\n    if y_true.shape[0] != y_pred.shape[0]:\n        raise ValueError(\"Batch size of y_true and y_pred must be equal.\")\n    if y_true.shape[1] != y_pred.shape[1]:\n        raise ValueError(\"Sentence length of y_true and y_pred must be equal.\")\n    if np.max(y_true) > vocab_size:\n        raise ValueError(\"Label value must not be greater than vocabulary size.\")\n\n    # Matrix to select prediction value only for true class\n    filter_matrix = np.array(\n        [[list(np.eye(vocab_size)[word]) for word in sentence] for sentence in y_true]\n    )\n\n    # Getting the matrix containing prediction for only true class\n    true_class_pred = np.sum(y_pred * filter_matrix, axis=2).clip(epsilon, 1)\n\n    # Calculating perplexity for each sentence\n    perp_losses = np.exp(np.negative(np.mean(np.log(true_class_pred), axis=1)))\n\n    return np.mean(perp_losses)\n","sourceCodeStart":538,"sourceCodeEnd":574,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/machine_learning/loss_functions.py#L538-L574","documentation":"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.","triggerScenarios":"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.","commonSituations":"Reference corpus and model output built from different batch sizes; last partial batch handled inconsistently; extra sample appended during decoding.","solutions":["Slice to a common batch: n = min(len(y_true), len(y_pred)); use y_true[:n], y_pred[:n].","Regenerate y_pred with the exact batch the references were built from.","Verify y_true.shape == y_pred.shape[:2] before the call."],"exampleFix":"# before\nloss = perplexity_loss(y_true, y_pred)  # y_true has 2 sentences, y_pred has 3\n\n# after\nn = min(y_true.shape[0], y_pred.shape[0])\nloss = perplexity_loss(y_true[:n], y_pred[:n])","handlingStrategy":"validation","validationCode":"assert y_true.shape[0] == y_pred.shape[0]\nassert y_true.shape[1] == y_pred.shape[1]\nloss = perplexity_loss(y_true, y_pred)","typeGuard":"def perplexity_shapes_ok(y_true: np.ndarray, y_pred: np.ndarray) -> bool:\n    return (\n        y_pred.ndim == 3\n        and y_true.ndim == 2\n        and y_true.shape == y_pred.shape[:2]\n    )","tryCatchPattern":null,"preventionTips":["Build y_true and y_pred in the same loop so batch and sequence dims cannot diverge.","Handle the last partial batch identically for references and predictions.","Add a shape check helper before any LLM evaluation run."],"tags":["machine-learning","loss-function","nlp","perplexity"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}