TheAlgorithms/Python · error · ValueError
Input arrays must have the same length.
Error message
Input arrays must have the same length.
What it means
Raised by binary_cross_entropy when y_true and y_pred have different lengths. The loss is averaged elementwise over paired entries, so mismatched arrays cannot be combined and the function validates len() equality before computing.
Source
Thrown at machine_learning/loss_functions.py:35
Parameters:
- y_true: True binary labels (0 or 1)
- y_pred: Predicted probabilities for class 1
- epsilon: Small constant to avoid numerical instability
>>> true_labels = np.array([0, 1, 1, 0, 1])
>>> predicted_probs = np.array([0.2, 0.7, 0.9, 0.3, 0.8])
>>> float(binary_cross_entropy(true_labels, predicted_probs))
0.2529995012327421
>>> true_labels = np.array([0, 1, 1, 0, 1])
>>> predicted_probs = np.array([0.3, 0.8, 0.9, 0.2])
>>> binary_cross_entropy(true_labels, predicted_probs)
Traceback (most recent call last):
...
ValueError: Input arrays must have the same length.
"""
if len(y_true) != len(y_pred):
raise ValueError("Input arrays must have the same length.")
y_pred = np.clip(y_pred, epsilon, 1 - epsilon) # Clip predictions to avoid log(0)
bce_loss = -(y_true * np.log(y_pred) + (1 - y_true) * np.log(1 - y_pred))
return np.mean(bce_loss)
def binary_focal_cross_entropy(
y_true: np.ndarray,
y_pred: np.ndarray,
gamma: float = 2.0,
alpha: float = 0.25,
epsilon: float = 1e-15,
) -> float:
"""
Calculate the mean binary focal cross-entropy (BFCE) loss between true labels
and predicted probabilities.
BFCE loss quantifies dissimilarity between true labels (0 or 1) and predictedView on GitHub (pinned to f5988cc097)
Solutions
- Verify shapes before the call: assert y_true.shape == y_pred.shape.
- Recompute predictions on the exact rows the labels correspond to.
- Filter both arrays with the same mask when cleaning data.
Example fix
# before y_pred = model.predict(X_all) binary_cross_entropy(y_test, y_pred) # lengths differ # after y_pred = model.predict(X_test) binary_cross_entropy(y_test, 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 = binary_cross_entropy(y_true, y_pred) Type guard
def same_length(a: np.ndarray, b: np.ndarray) -> bool:
return len(a) == len(b) Try / catch
try:
binary_cross_entropy(y_true, y_pred)
except ValueError as e:
if "same length" in str(e):
raise ValueError(f"labels/preds misaligned: {len(y_true)} vs {len(y_pred)}") from e
raise Prevention
- Generate predictions with the same batching as labels.
- Apply identical NaN masks to both arrays.
- Standardize one loss-input helper across the eval loop.
When it happens
Trigger: Calling binary_cross_entropy(np.array([0,1,1,0,1]), np.array([0.3,0.8,0.9,0.2])) — 5 labels vs 4 predictions, as in the doctest.
Common situations: Train/test split applied to labels but not predictions, dropping NaN rows from one array only, or evaluating a model that outputs a different batch size than the labels.
Related errors
- x and y have different lengths
- Input arrays must have the same shape.
- y_true must be one-hot encoded.
- Predicted probabilities must sum to approximately 1.
- Shape of y_true and y_pred must be the same.
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/8f44735bec3d2f4f.
Report an issue: GitHub.