{"record":{"id":"0a8f9344b190fb49","repo":"TheAlgorithms/Python","slug":"shape-of-y-true-and-y-pred-must-be-the-same","errorCode":null,"errorMessage":"Shape of y_true and y_pred must be the same.","messagePattern":"Shape of y_true and y_pred must be the same\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"machine_learning/loss_functions.py","lineNumber":228,"sourceCode":"    ValueError: y_true must be one-hot encoded.\n\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_focal_cross_entropy(true_labels, pred_probs)\n    Traceback (most recent call last):\n        ...\n    ValueError: Predicted probabilities must sum to approximately 1.\n\n    >>> true_labels = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n    >>> pred_probs = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1], [0.0, 0.1, 0.9]])\n    >>> alpha = np.array([0.6, 0.2])\n    >>> categorical_focal_cross_entropy(true_labels, pred_probs, alpha)\n    Traceback (most recent call last):\n        ...\n    ValueError: Length of alpha must match the number of classes.\n    \"\"\"\n    if y_true.shape != y_pred.shape:\n        raise ValueError(\"Shape of y_true and y_pred must be the same.\")\n\n    if alpha is None:\n        alpha = np.ones(y_true.shape[1])\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 len(alpha) != y_true.shape[1]:\n        raise ValueError(\"Length of alpha must match the number of classes.\")\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    # Clip predicted probabilities to avoid log(0)\n    y_pred = np.clip(y_pred, epsilon, 1 - epsilon)\n\n    # Calculate loss for each class and sum across classes\n    cfce_loss = -np.sum(","sourceCodeStart":210,"sourceCodeEnd":246,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/machine_learning/loss_functions.py#L210-L246","documentation":"Thrown by categorical_focal_cross_entropy when the y_true (one-hot labels) and y_pred (predicted probabilities) matrices have different shapes. The loss is computed element-wise (alpha * (1 - y_pred)^gamma * y_true * log(y_pred)), so both inputs must have identical dimensions (samples x classes). Any shape divergence makes the element-wise product undefined, hence the early validation.","triggerScenarios":"Calling categorical_focal_cross_entropy(y_true, y_pred) where y_true.shape != y_pred.shape, e.g. labels one-hot encoded over 3 classes but predictions over 4 classes, or a 1-D label array paired with a 2-D probability matrix.","commonSituations":"Mismatch between the number of output units of the model and the one-hot encoder; forgetting to one-hot encode y_true (passing integer class labels of shape (N,) against y_pred of shape (N, C)); transposed predictions; batch slicing that drops a dimension.","solutions":["Print y_true.shape and y_pred.shape right before the call and make them equal, typically (num_samples, num_classes).","One-hot encode y_true with the same num_classes as y_pred's last axis (e.g. np.eye(num_classes)[y_true_int]).","If y_pred was transposed or reshaped during preprocessing, fix the reshaping so rows are samples and columns are classes.","Verify the model's final dense layer size matches the number of classes in the label encoder."],"exampleFix":"# before\ny_true = np.array([0, 2, 1])              # shape (3,)\nloss = categorical_focal_cross_entropy(y_true, y_pred)  # y_pred shape (3, 3)\n\n# after\ny_true = np.eye(y_pred.shape[1])[y_true]   # shape (3, 3)\nloss = categorical_focal_cross_entropy(y_true, y_pred)","handlingStrategy":"validation","validationCode":"if y_true.shape != y_pred.shape:\n    raise ValueError(f\"shape mismatch: {y_true.shape} vs {y_pred.shape}\")\nloss = categorical_focal_cross_entropy(y_true, y_pred, alpha)","typeGuard":"def is_valid_cfce_input(y_true: np.ndarray, y_pred: np.ndarray) -> bool:\n    return y_true.ndim == 2 and y_true.shape == y_pred.shape","tryCatchPattern":"try:\n    loss = categorical_focal_cross_entropy(y_true, y_pred, alpha)\nexcept ValueError as e:\n    logger.error(\"focal loss input invalid: %s; shapes %s vs %s\", e, y_true.shape, y_pred.shape)\n    raise","preventionTips":["One-hot encode labels with np.eye(num_classes) where num_classes equals y_pred.shape[1].","Assert identical shapes in the data-prep pipeline before training loops.","Keep model output layer size and label encoder class count derived from one shared constant."],"tags":["machine-learning","loss-function","shape-mismatch","numpy"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}