Softmax Cross-Entropy Loss
You are given a vector of predicted class probabilities and the index of the true class. Your task is to compute the cross-entropy loss, which measures how well the predicted distribution matches the true label.
The Cross-Entropy Loss for classification is defined as:
Where:
- is the vector of predicted probabilities (must sum to 1)
- is the index of the true class
- is the predicted probability for the true class
This loss function:
- Returns 0 when the model is perfectly confident in the correct class ()
- Approaches infinity as confidence in the correct class approaches 0
- Heavily penalizes confident but wrong predictions
Round output to 4 decimal places.
Example
probs = [0.7, 0.2, 0.1] true_class = 0
0.3567
- Inputs:
probsis the model's predicted distribution over 3 classes, , which sums to 1.true_classis , so the correct label is the first class. - Pick the relevant probability: only the entry for the true class matters, . The probabilities and given to the wrong classes do not enter the formula directly (they only matter because they take mass away from ).
- Apply the loss: . Since , its natural log is negative, , so the minus sign makes the loss positive: .
- Output: a single non-negative number, rounded to 4 decimal places:
0.3567. - Notice that the loss grows quickly as shrinks: had the true class been index 2 (with ), the loss would be , more than six times larger. A perfect would give exactly 0.
Constraints
- probs is a list of probabilities that sum to 1
- All probabilities are positive (> 0)
- true_class is a valid index (0 to len(probs)-1)
- Return the loss rounded to 4 decimal places