{"record":{"id":"a9bb4fe7d57da68c","repo":"TheAlgorithms/Python","slug":"length-of-alpha-must-match-the-number-of-classes","errorCode":null,"errorMessage":"Length of alpha must match the number of classes.","messagePattern":"Length of alpha must match the number of classes\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"machine_learning/loss_functions.py","lineNumber":237,"sourceCode":"    >>> 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(\n        alpha * np.power(1 - y_pred, gamma) * y_true * np.log(y_pred), axis=1\n    )\n\n    return np.mean(cfce_loss)\n\n\ndef hinge_loss(y_true: np.ndarray, y_pred: np.ndarray) -> float:\n    \"\"\"\n    Calculate the mean hinge loss for between true labels and predicted probabilities","sourceCodeStart":219,"sourceCodeEnd":255,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/machine_learning/loss_functions.py#L219-L255","documentation":"Thrown by categorical_focal_cross_entropy when the alpha weighting vector's length differs from the number of classes (y_true.shape[1]). alpha per-class weights the focal term, so it must have one entry per class column. Note that when alpha=None it defaults to uniform ones, so this error only fires for an explicitly supplied alpha.","triggerScenarios":"Passing alpha = np.array([0.6, 0.2]) with a 3-class problem; passing a scalar alpha instead of a per-class list; reusing an alpha tuned for a different model with a different class count.","commonSituations":"Changing the number of classes (new category added) without updating class weights; copying alpha vectors from tutorials with different class counts; passing class-weight dicts from sklearn instead of arrays.","solutions":["Set alpha = np.full(num_classes, 1.0) or None for uniform weighting, or supply one weight per class: alpha = np.array([0.6, 0.2, 0.2]).","Derive alpha programmatically from the data: alpha = compute_class_weight('balanced', classes=np.arange(C), y=y_int).","Confirm num_classes = y_true.shape[1] and len(alpha) match before the call."],"exampleFix":"# before\nalpha = np.array([0.6, 0.2])            # 2 weights, 3 classes\nloss = categorical_focal_cross_entropy(y_true, y_pred, alpha)\n\n# after\nalpha = np.array([0.6, 0.3, 0.1])       # one weight per class\nloss = categorical_focal_cross_entropy(y_true, y_pred, alpha)","handlingStrategy":"validation","validationCode":"num_classes = y_true.shape[1]\nif alpha is None or len(alpha) != num_classes:\n    alpha = np.full(num_classes, 1.0)\nloss = categorical_focal_cross_entropy(y_true, y_pred, alpha)","typeGuard":"def alpha_matches(alpha: np.ndarray | None, num_classes: int) -> bool:\n    return alpha is None or (isinstance(alpha, np.ndarray) and alpha.shape == (num_classes,))","tryCatchPattern":null,"preventionTips":["Derive alpha length from y_true.shape[1] programmatically, never hardcode it.","Default to None (uniform weights) unless class imbalance demands otherwise.","Recompute class weights whenever the number of classes changes."],"tags":["machine-learning","loss-function","focal-loss","class-weights"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}