TheAlgorithms/Python · error · ValueError

Length of predicted and actual array must be same.

Error message

Length of predicted and actual array must be same.

What it means

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.

Source

Thrown at machine_learning/loss_functions.py:284

    >>> true_labels = np.array([-1, 1, 1, -1, 1])
    >>> pred = np.array([-4, -0.3, 0.7, 5, 10])
    >>> float(hinge_loss(true_labels, pred))
    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

View on GitHub (pinned to f5988cc097)

Solutions

  1. Verify len(y_true) == len(y_pred) immediately before the call and trim or rebuild the misaligned array.
  2. Regenerate predictions from the same X that produced y_true: y_pred = decision_function(X).
  3. Flatten both arrays consistently: y_true.ravel() and y_pred.ravel().

Example fix

# before
y_true = np.array([-1, 1, 1, -1, 1])
y_pred = np.array([-4, -0.3, 0.7, 5])   # 4 entries
hinge_loss(y_true, y_pred)

# after
y_pred = np.array([-4, -0.3, 0.7, 5, 10])
hinge_loss(y_true, y_pred)
Defensive patterns

Strategy: validation

Validate before calling

assert len(y_true) == len(y_pred), f"{len(y_true)} labels vs {len(y_pred)} preds"
loss = hinge_loss(y_true, y_pred)

Type guard

def aligned_1d(y_true: np.ndarray, y_pred: np.ndarray) -> bool:
    return y_true.ndim == 1 and y_pred.ndim == 1 and y_true.shape == y_pred.shape

Prevention

When it happens

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

Common situations: Off-by-one slicing of predictions; train/test split applied to labels but not predictions; misaligned minibatches; predictions flattened while labels were not.

Related errors


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