{"record":{"id":"19ce8f8dfc7a4f71","repo":"TheAlgorithms/Python","slug":"length-of-predicted-and-actual-array-must-be-same","errorCode":null,"errorMessage":"Length of predicted and actual array must be same.","messagePattern":"Length of predicted and actual array must be same\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"machine_learning/loss_functions.py","lineNumber":284,"sourceCode":"    >>> true_labels = np.array([-1, 1, 1, -1, 1])\n    >>> pred = np.array([-4, -0.3, 0.7, 5, 10])\n    >>> float(hinge_loss(true_labels, pred))\n    1.52\n    >>> true_labels = np.array([-1, 1, 1, -1, 1, 1])\n    >>> pred = np.array([-4, -0.3, 0.7, 5, 10])\n    >>> hinge_loss(true_labels, pred)\n    Traceback (most recent call last):\n    ...\n    ValueError: Length of predicted and actual array must be same.\n    >>> true_labels = np.array([-1, 1, 10, -1, 1])\n    >>> pred = np.array([-4, -0.3, 0.7, 5, 10])\n    >>> hinge_loss(true_labels, pred)\n    Traceback (most recent call last):\n    ...\n    ValueError: y_true can have values -1 or 1 only.\n    \"\"\"\n    if len(y_true) != len(y_pred):\n        raise ValueError(\"Length of predicted and actual array must be same.\")\n\n    if np.any((y_true != -1) & (y_true != 1)):\n        raise ValueError(\"y_true can have values -1 or 1 only.\")\n\n    hinge_losses = np.maximum(0, 1.0 - (y_true * y_pred))\n    return np.mean(hinge_losses)\n\n\ndef huber_loss(y_true: np.ndarray, y_pred: np.ndarray, delta: float) -> float:\n    \"\"\"\n    Calculate the mean Huber loss between the given ground truth and predicted values.\n\n    The Huber loss describes the penalty incurred by an estimation procedure, and it\n    serves as a measure of accuracy for regression models.\n\n    Huber loss =\n        0.5 * (y_true - y_pred)^2                   if |y_true - y_pred| <= delta\n        delta * |y_true - y_pred| - 0.5 * delta^2   otherwise","sourceCodeStart":266,"sourceCodeEnd":302,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/machine_learning/loss_functions.py#L266-L302","documentation":"Thrown by hinge_loss when y_true and y_pred have different lengths. Hinge loss is computed pairwise as max(0, 1 - y_true * y_pred) and then averaged, so both 1-D arrays must contain one entry per sample.","triggerScenarios":"Calling hinge_loss(y_true, y_pred) with len(y_true) != len(y_pred), e.g. 5 labels against 4 scores, or comparing a 2-D batch against a 1-D label vector.","commonSituations":"Off-by-one slicing of predictions; train/test split applied to labels but not predictions; misaligned minibatches; predictions flattened while labels were not.","solutions":["Verify len(y_true) == len(y_pred) immediately before the call and trim or rebuild the misaligned array.","Regenerate predictions from the same X that produced y_true: y_pred = decision_function(X).","Flatten both arrays consistently: y_true.ravel() and y_pred.ravel()."],"exampleFix":"# before\ny_true = np.array([-1, 1, 1, -1, 1])\ny_pred = np.array([-4, -0.3, 0.7, 5])   # 4 entries\nhinge_loss(y_true, y_pred)\n\n# after\ny_pred = np.array([-4, -0.3, 0.7, 5, 10])\nhinge_loss(y_true, y_pred)","handlingStrategy":"validation","validationCode":"assert len(y_true) == len(y_pred), f\"{len(y_true)} labels vs {len(y_pred)} preds\"\nloss = hinge_loss(y_true, y_pred)","typeGuard":"def aligned_1d(y_true: np.ndarray, y_pred: np.ndarray) -> bool:\n    return y_true.ndim == 1 and y_pred.ndim == 1 and y_true.shape == y_pred.shape","tryCatchPattern":null,"preventionTips":["Generate y_pred from the same X that produced y_true.","Flatten both arrays with .ravel() before calling.","Wrap metric evaluation in a helper that asserts alignment once."],"tags":["machine-learning","loss-function","svm","shape-mismatch"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}