{"record":{"id":"d6fd268cc622200f","repo":"TheAlgorithms/Python","slug":"input-arrays-must-have-the-same-shape","errorCode":null,"errorMessage":"Input arrays must have the same shape.","messagePattern":"Input arrays must have the same shape\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"machine_learning/loss_functions.py","lineNumber":139,"sourceCode":"    >>> categorical_cross_entropy(true_labels, pred_probs)\n    Traceback (most recent call last):\n        ...\n    ValueError: y_true must be one-hot encoded.\n    >>> true_labels = np.array([[1, 0, 1], [1, 0, 0]])\n    >>> pred_probs = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1]])\n    >>> categorical_cross_entropy(true_labels, pred_probs)\n    Traceback (most recent call last):\n        ...\n    ValueError: y_true must be one-hot encoded.\n    >>> true_labels = np.array([[1, 0, 0], [0, 1, 0]])\n    >>> pred_probs = np.array([[0.9, 0.1, 0.1], [0.2, 0.7, 0.1]])\n    >>> categorical_cross_entropy(true_labels, pred_probs)\n    Traceback (most recent call last):\n        ...\n    ValueError: Predicted probabilities must sum to approximately 1.\n    \"\"\"\n    if y_true.shape != y_pred.shape:\n        raise ValueError(\"Input arrays must have the same shape.\")\n\n    if np.any((y_true != 0) & (y_true != 1)) or np.any(y_true.sum(axis=1) != 1):\n        raise ValueError(\"y_true must be one-hot encoded.\")\n\n    if not np.all(np.isclose(np.sum(y_pred, axis=1), 1, rtol=epsilon, atol=epsilon)):\n        raise ValueError(\"Predicted probabilities must sum to approximately 1.\")\n\n    y_pred = np.clip(y_pred, epsilon, 1)  # Clip predictions to avoid log(0)\n    return -np.sum(y_true * np.log(y_pred))\n\n\ndef categorical_focal_cross_entropy(\n    y_true: np.ndarray,\n    y_pred: np.ndarray,\n    alpha: np.ndarray = None,\n    gamma: float = 2.0,\n    epsilon: float = 1e-15,\n) -> float:","sourceCodeStart":121,"sourceCodeEnd":157,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/machine_learning/loss_functions.py#L121-L157","documentation":"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.","triggerScenarios":"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.","commonSituations":"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).","solutions":["Make both arrays (n_samples, n_classes) with the same n_classes.","If y_true is integer class indices, one-hot encode it first (np.eye(k)[labels]).","If y_pred came out transposed, pass y_pred.T or fix the model output layout."],"exampleFix":"# before\ny_true = np.eye(3)[labels]         # (n, 3)\ny_pred = model_output               # (n, 5)\ncategorical_cross_entropy(y_true, y_pred)\n\n# after\nassert y_true.shape == y_pred.shape\ncategorical_cross_entropy(y_true, 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 = categorical_cross_entropy(y_true, y_pred)","typeGuard":"def same_shape_2d(y_true: np.ndarray, y_pred: np.ndarray) -> bool:\n    return y_true.shape == y_pred.shape and y_true.ndim == 2","tryCatchPattern":"try:\n    categorical_cross_entropy(y_true, y_pred)\nexcept ValueError as e:\n    if \"same shape\" in str(e):\n        raise ValueError(f\"re-encode labels to {y_pred.shape[1]} classes\") from e\n    raise","preventionTips":["Keep the class-count dimension consistent between labels and model head.","One-hot encode integer labels with np.eye(n_classes).","Check for accidental transposes of prediction matrices."],"tags":["machine-learning","loss-function","cross-entropy","shape-mismatch"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}