{"record":{"id":"5f008444776167f5","repo":"TheAlgorithms/Python","slug":"the-length-of-the-two-arrays-should-be-the-same","errorCode":null,"errorMessage":"The length of the two arrays should be the same.","messagePattern":"The length of the two arrays should be the same\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"machine_learning/loss_functions.py","lineNumber":476,"sourceCode":"\n    Examples:\n    >>> y_true = np.array([10, 20, 30, 40])\n    >>> y_pred = np.array([12, 18, 33, 45])\n    >>> float(mean_absolute_percentage_error(y_true, y_pred))\n    0.13125\n\n    >>> y_true = np.array([1, 2, 3, 4])\n    >>> y_pred = np.array([2, 3, 4, 5])\n    >>> float(mean_absolute_percentage_error(y_true, y_pred))\n    0.5208333333333333\n\n    >>> y_true = np.array([34, 37, 44, 47, 48, 48, 46, 43, 32, 27, 26, 24])\n    >>> y_pred = np.array([37, 40, 46, 44, 46, 50, 45, 44, 34, 30, 22, 23])\n    >>> float(mean_absolute_percentage_error(y_true, y_pred))\n    0.064671076436071\n    \"\"\"\n    if len(y_true) != len(y_pred):\n        raise ValueError(\"The length of the two arrays should be the same.\")\n\n    y_true = np.where(y_true == 0, epsilon, y_true)\n    absolute_percentage_diff = np.abs((y_true - y_pred) / y_true)\n\n    return np.mean(absolute_percentage_diff)\n\n\ndef perplexity_loss(\n    y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-7\n) -> float:\n    \"\"\"\n    Calculate the perplexity for the y_true and y_pred.\n\n    Compute the Perplexity which useful in predicting language model\n    accuracy in Natural Language Processing (NLP.)\n    Perplexity is measure of how certain the model in its predictions.\n\n    Perplexity Loss = exp(-1/N (Σ ln(p(x)))","sourceCodeStart":458,"sourceCodeEnd":494,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/machine_learning/loss_functions.py#L458-L494","documentation":"Thrown by mean_absolute_percentage_error when y_true and y_pred have different lengths. MAPE averages |(y_true - y_pred)/y_true| per element, so both arrays must be aligned; zero y_true entries are replaced by epsilon to avoid division by zero.","triggerScenarios":"Calling mean_absolute_percentage_error with len(y_true) != len(y_pred), e.g. 4 truth values vs 4 predictions is fine but 4 vs 5 raises.","commonSituations":"Time-series evaluation where predicted horizon length differs from the label window; dataframes aligned by index with NaNs dropped in one column only.","solutions":["Align both arrays to the same evaluation window before computing MAPE.","If using pandas, drop NaN rows jointly: df = df.dropna(subset=['y_true','y_pred']).","Add an assert len(y_true) == len(y_pred) guard in the eval script."],"exampleFix":"# before\ny_true = np.array([1, 2, 3])\ny_pred = np.array([2, 3, 4, 5])\nmean_absolute_percentage_error(y_true, y_pred)\n\n# after\ny_true = np.array([1, 2, 3, 4])\nmean_absolute_percentage_error(y_true, y_pred)","handlingStrategy":"validation","validationCode":"assert len(y_true) == len(y_pred)\nmape = mean_absolute_percentage_error(y_true, y_pred)","typeGuard":"def same_length(y_true: np.ndarray, y_pred: np.ndarray) -> bool:\n    return len(y_true) == len(y_pred)","tryCatchPattern":null,"preventionTips":["In pandas, dropna jointly over both columns before extracting arrays.","Treat zero y_true values carefully: they are silently replaced by epsilon here, which can inflate MAPE.","Standardize the evaluation window length across all metrics."],"tags":["machine-learning","loss-function","metrics","time-series"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}