TheAlgorithms/Python · error · ValueError

y_true can have values -1 or 1 only.

Error message

y_true can have values -1 or 1 only.

What it means

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.

Source

Thrown at machine_learning/loss_functions.py:287

    1.52
    >>> true_labels = np.array([-1, 1, 1, -1, 1, 1])
    >>> pred = np.array([-4, -0.3, 0.7, 5, 10])
    >>> hinge_loss(true_labels, pred)
    Traceback (most recent call last):
    ...
    ValueError: Length of predicted and actual array must be same.
    >>> true_labels = np.array([-1, 1, 10, -1, 1])
    >>> pred = np.array([-4, -0.3, 0.7, 5, 10])
    >>> hinge_loss(true_labels, pred)
    Traceback (most recent call last):
    ...
    ValueError: y_true can have values -1 or 1 only.
    """
    if len(y_true) != len(y_pred):
        raise ValueError("Length of predicted and actual array must be same.")

    if np.any((y_true != -1) & (y_true != 1)):
        raise ValueError("y_true can have values -1 or 1 only.")

    hinge_losses = np.maximum(0, 1.0 - (y_true * y_pred))
    return np.mean(hinge_losses)


def huber_loss(y_true: np.ndarray, y_pred: np.ndarray, delta: float) -> float:
    """
    Calculate the mean Huber loss between the given ground truth and predicted values.

    The Huber loss describes the penalty incurred by an estimation procedure, and it
    serves as a measure of accuracy for regression models.

    Huber loss =
        0.5 * (y_true - y_pred)^2                   if |y_true - y_pred| <= delta
        delta * |y_true - y_pred| - 0.5 * delta^2   otherwise

    Reference: https://en.wikipedia.org/wiki/Huber_loss

View on GitHub (pinned to f5988cc097)

Solutions

  1. Convert 0/1 labels: y_true = np.where(y_true == 1, 1, -1) or 2*y_true - 1.
  2. If labels are multiclass, use a multiclass loss (categorical cross-entropy / focal) or one-vs-rest binarization per class.
  3. Assert np.isin(y_true, [-1, 1]).all() in data-prep pipelines.

Example fix

# before
y_true = np.array([0, 1, 1, 0, 1])
hinge_loss(y_true, y_pred)

# after
y_true = np.where(y_true == 1, 1, -1)
hinge_loss(y_true, y_pred)
Defensive patterns

Strategy: validation

Validate before calling

if not np.isin(y_true, [-1, 1]).all():
    y_true = np.where(y_true > 0, 1, -1)
loss = hinge_loss(y_true, y_pred)

Type guard

def is_pm1_labels(y_true: np.ndarray) -> bool:
    return np.isin(y_true, [-1, 1]).all()

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


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