TheAlgorithms/Python · error · ValueError

Input arrays must have the same shape.

Error message

Input arrays must have the same shape.

What it means

Raised by categorical_cross_entropy when y_true.shape != y_pred.shape. Unlike the binary losses which check only lengths, the categorical version needs exact shape equality because it sums one-hot rows against predicted probability rows elementwise, including the per-row sum(axis=1) validation.

Source

Thrown at machine_learning/loss_functions.py:139

    >>> categorical_cross_entropy(true_labels, pred_probs)
    Traceback (most recent call last):
        ...
    ValueError: y_true must be one-hot encoded.
    >>> true_labels = np.array([[1, 0, 1], [1, 0, 0]])
    >>> pred_probs = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1]])
    >>> categorical_cross_entropy(true_labels, pred_probs)
    Traceback (most recent call last):
        ...
    ValueError: y_true must be one-hot encoded.
    >>> true_labels = np.array([[1, 0, 0], [0, 1, 0]])
    >>> pred_probs = np.array([[0.9, 0.1, 0.1], [0.2, 0.7, 0.1]])
    >>> categorical_cross_entropy(true_labels, pred_probs)
    Traceback (most recent call last):
        ...
    ValueError: Predicted probabilities must sum to approximately 1.
    """
    if y_true.shape != y_pred.shape:
        raise ValueError("Input arrays must have the same shape.")

    if np.any((y_true != 0) & (y_true != 1)) or np.any(y_true.sum(axis=1) != 1):
        raise ValueError("y_true must be one-hot encoded.")

    if not np.all(np.isclose(np.sum(y_pred, axis=1), 1, rtol=epsilon, atol=epsilon)):
        raise ValueError("Predicted probabilities must sum to approximately 1.")

    y_pred = np.clip(y_pred, epsilon, 1)  # Clip predictions to avoid log(0)
    return -np.sum(y_true * np.log(y_pred))


def categorical_focal_cross_entropy(
    y_true: np.ndarray,
    y_pred: np.ndarray,
    alpha: np.ndarray = None,
    gamma: float = 2.0,
    epsilon: float = 1e-15,
) -> float:

View on GitHub (pinned to f5988cc097)

Solutions

  1. Make both arrays (n_samples, n_classes) with the same n_classes.
  2. If y_true is integer class indices, one-hot encode it first (np.eye(k)[labels]).
  3. If y_pred came out transposed, pass y_pred.T or fix the model output layout.

Example fix

# before
y_true = np.eye(3)[labels]         # (n, 3)
y_pred = model_output               # (n, 5)
categorical_cross_entropy(y_true, y_pred)

# after
assert y_true.shape == y_pred.shape
categorical_cross_entropy(y_true, y_pred)
Defensive patterns

Strategy: validation

Validate before calling

y_true = np.asarray(y_true)
y_pred = np.asarray(y_pred)
assert y_true.shape == y_pred.shape, f"{y_true.shape} vs {y_pred.shape}"
loss = categorical_cross_entropy(y_true, y_pred)

Type guard

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

Try / catch

try:
    categorical_cross_entropy(y_true, y_pred)
except ValueError as e:
    if "same shape" in str(e):
        raise ValueError(f"re-encode labels to {y_pred.shape[1]} classes") from e
    raise

Prevention

When it happens

Trigger: Passing y_true of shape (n, k) with y_pred of shape (n, m) (different class counts), or a one-hot 2D y_true against a flattened 1D prediction vector.

Common situations: Changing the number of output units without regenerating one-hot labels, mixing shapes between binary (n,) and categorical (n, k) conventions, or transposing predictions from a model that emits (k, n).

Related errors


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