TheAlgorithms/Python · error · ValueError
Length of alpha must match the number of classes.
Error message
Length of alpha must match the number of classes.
What it means
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.
Source
Thrown at machine_learning/loss_functions.py:237
>>> true_labels = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
>>> pred_probs = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1], [0.0, 0.1, 0.9]])
>>> alpha = np.array([0.6, 0.2])
>>> categorical_focal_cross_entropy(true_labels, pred_probs, alpha)
Traceback (most recent call last):
...
ValueError: Length of alpha must match the number of classes.
"""
if y_true.shape != y_pred.shape:
raise ValueError("Shape of y_true and y_pred must be the same.")
if alpha is None:
alpha = np.ones(y_true.shape[1])
if np.any((y_true != 0) & (y_true != 1)) or np.any(y_true.sum(axis=1) != 1):
raise ValueError("y_true must be one-hot encoded.")
if len(alpha) != y_true.shape[1]:
raise ValueError("Length of alpha must match the number of classes.")
if not np.all(np.isclose(np.sum(y_pred, axis=1), 1, rtol=epsilon, atol=epsilon)):
raise ValueError("Predicted probabilities must sum to approximately 1.")
# Clip predicted probabilities to avoid log(0)
y_pred = np.clip(y_pred, epsilon, 1 - epsilon)
# Calculate loss for each class and sum across classes
cfce_loss = -np.sum(
alpha * np.power(1 - y_pred, gamma) * y_true * np.log(y_pred), axis=1
)
return np.mean(cfce_loss)
def hinge_loss(y_true: np.ndarray, y_pred: np.ndarray) -> float:
"""
Calculate the mean hinge loss for between true labels and predicted probabilitiesView on GitHub (pinned to f5988cc097)
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.
Example fix
# before alpha = np.array([0.6, 0.2]) # 2 weights, 3 classes loss = categorical_focal_cross_entropy(y_true, y_pred, alpha) # after alpha = np.array([0.6, 0.3, 0.1]) # one weight per class loss = categorical_focal_cross_entropy(y_true, y_pred, alpha)
Defensive patterns
Strategy: validation
Validate before calling
num_classes = y_true.shape[1]
if alpha is None or len(alpha) != num_classes:
alpha = np.full(num_classes, 1.0)
loss = categorical_focal_cross_entropy(y_true, y_pred, alpha) Type guard
def alpha_matches(alpha: np.ndarray | None, num_classes: int) -> bool:
return alpha is None or (isinstance(alpha, np.ndarray) and alpha.shape == (num_classes,)) Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- Input arrays must have the same length.
- Input arrays must have the same shape.
- y_true must be one-hot encoded.
- Predicted probabilities must sum to approximately 1.
- Shape of y_true and y_pred must be the same.
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/a9bb4fe7d57da68c.
Report an issue: GitHub.