{"record":{"id":"29d3e4948434a9d2","repo":"TheAlgorithms/Python","slug":"y-true-can-have-values-1-or-1-only","errorCode":null,"errorMessage":"y_true can have values -1 or 1 only.","messagePattern":"y_true can have values -1 or 1 only\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"machine_learning/loss_functions.py","lineNumber":287,"sourceCode":"    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\n\n    Reference: https://en.wikipedia.org/wiki/Huber_loss\n","sourceCodeStart":269,"sourceCodeEnd":305,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/machine_learning/loss_functions.py#L269-L305","documentation":"Thrown by hinge_loss when y_true contains values other than exactly -1 or 1. The hinge formulation max(0, 1 - y*y_pred) is defined for margin labels in {-1, +1}; labels like 0/1, 10, or 2 make the loss meaningless, so the function rejects them.","triggerScenarios":"Passing binary labels encoded as 0/1; passing multiclass integer labels (e.g. 10); passing floats like -1.0/1.0 is fine but 0.5 or 2 is not.","commonSituations":"Dataset ships with labels in {0,1} (common in pandas/sklearn) and is fed directly to a hinge/SVM loss; label encoding step forgotten; multiclass labels fed to a binary hinge implementation.","solutions":["Convert 0/1 labels: y_true = np.where(y_true == 1, 1, -1) or 2*y_true - 1.","If labels are multiclass, use a multiclass loss (categorical cross-entropy / focal) or one-vs-rest binarization per class.","Assert np.isin(y_true, [-1, 1]).all() in data-prep pipelines."],"exampleFix":"# before\ny_true = np.array([0, 1, 1, 0, 1])\nhinge_loss(y_true, y_pred)\n\n# after\ny_true = np.where(y_true == 1, 1, -1)\nhinge_loss(y_true, y_pred)","handlingStrategy":"validation","validationCode":"if not np.isin(y_true, [-1, 1]).all():\n    y_true = np.where(y_true > 0, 1, -1)\nloss = hinge_loss(y_true, y_pred)","typeGuard":"def is_pm1_labels(y_true: np.ndarray) -> bool:\n    return np.isin(y_true, [-1, 1]).all()","tryCatchPattern":null,"preventionTips":["Convert 0/1 labels to -1/1 at data load time: 2 * y - 1.","Keep one canonical label-encoding step in the pipeline, not ad-hoc conversions.","Document the {-1, 1} contract wherever hinge loss is used."],"tags":["machine-learning","loss-function","svm","label-encoding"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}