{"record":{"id":"8f44735bec3d2f4f","repo":"TheAlgorithms/Python","slug":"input-arrays-must-have-the-same-length","errorCode":null,"errorMessage":"Input arrays must have the same length.","messagePattern":"Input arrays must have the same length\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"machine_learning/loss_functions.py","lineNumber":35,"sourceCode":"\n    Parameters:\n    - y_true: True binary labels (0 or 1)\n    - y_pred: Predicted probabilities for class 1\n    - epsilon: Small constant to avoid numerical instability\n\n    >>> true_labels = np.array([0, 1, 1, 0, 1])\n    >>> predicted_probs = np.array([0.2, 0.7, 0.9, 0.3, 0.8])\n    >>> float(binary_cross_entropy(true_labels, predicted_probs))\n    0.2529995012327421\n    >>> true_labels = np.array([0, 1, 1, 0, 1])\n    >>> predicted_probs = np.array([0.3, 0.8, 0.9, 0.2])\n    >>> binary_cross_entropy(true_labels, predicted_probs)\n    Traceback (most recent call last):\n        ...\n    ValueError: Input arrays must have the same length.\n    \"\"\"\n    if len(y_true) != len(y_pred):\n        raise ValueError(\"Input arrays must have the same length.\")\n\n    y_pred = np.clip(y_pred, epsilon, 1 - epsilon)  # Clip predictions to avoid log(0)\n    bce_loss = -(y_true * np.log(y_pred) + (1 - y_true) * np.log(1 - y_pred))\n    return np.mean(bce_loss)\n\n\ndef binary_focal_cross_entropy(\n    y_true: np.ndarray,\n    y_pred: np.ndarray,\n    gamma: float = 2.0,\n    alpha: float = 0.25,\n    epsilon: float = 1e-15,\n) -> float:\n    \"\"\"\n    Calculate the mean binary focal cross-entropy (BFCE) loss between true labels\n    and predicted probabilities.\n\n    BFCE loss quantifies dissimilarity between true labels (0 or 1) and predicted","sourceCodeStart":17,"sourceCodeEnd":53,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/machine_learning/loss_functions.py#L17-L53","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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."],"exampleFix":"# before\ny_pred = model.predict(X_all)\nbinary_cross_entropy(y_test, y_pred)  # lengths differ\n\n# after\ny_pred = model.predict(X_test)\nbinary_cross_entropy(y_test, y_pred)","handlingStrategy":"validation","validationCode":"y_true = np.asarray(y_true)\ny_pred = np.asarray(y_pred)\nassert y_true.shape == y_pred.shape, f\"{y_true.shape} vs {y_pred.shape}\"\nloss = binary_cross_entropy(y_true, y_pred)","typeGuard":"def same_length(a: np.ndarray, b: np.ndarray) -> bool:\n    return len(a) == len(b)","tryCatchPattern":"try:\n    binary_cross_entropy(y_true, y_pred)\nexcept ValueError as e:\n    if \"same length\" in str(e):\n        raise ValueError(f\"labels/preds misaligned: {len(y_true)} vs {len(y_pred)}\") from e\n    raise","preventionTips":["Generate predictions with the same batching as labels.","Apply identical NaN masks to both arrays.","Standardize one loss-input helper across the eval loop."],"tags":["machine-learning","loss-function","data-alignment","input-validation"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}