v9.1.1
Menu

Softmax Cross-Entropy Loss

mediumFREEImage ClassificationDeep LearningCV: Recognition

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:

L=−log⁡(py)L = -\log(p_y)

Where:

  • pp is the vector of predicted probabilities (must sum to 1)
  • yy is the index of the true class
  • pyp_y is the predicted probability for the true class

This loss function:

  1. Returns 0 when the model is perfectly confident in the correct class (py=1p_y = 1)
  2. Approaches infinity as confidence in the correct class approaches 0
  3. Heavily penalizes confident but wrong predictions

Round output to 4 decimal places.

Example

Input
probs = [0.7, 0.2, 0.1]
true_class = 0
Output
0.3567
Reasoning
  • Inputs: probs is the model's predicted distribution over 3 classes, p=(0.7,0.2,0.1)p = (0.7, 0.2, 0.1), which sums to 1. true_class is y=0y = 0, so the correct label is the first class.
  • Pick the relevant probability: only the entry for the true class matters, py=p0=0.7p_y = p_0 = 0.7. The probabilities 0.20.2 and 0.10.1 given to the wrong classes do not enter the formula directly (they only matter because they take mass away from p0p_0).
  • Apply the loss: L=−ln⁡(0.7)L = -\ln(0.7). Since 0.7<10.7 < 1, its natural log is negative, ln⁡(0.7)≈−0.35667\ln(0.7) \approx -0.35667, so the minus sign makes the loss positive: L≈0.35667L \approx 0.35667.
  • Output: a single non-negative number, rounded to 4 decimal places: 0.3567.
  • Notice that the loss grows quickly as pyp_y shrinks: had the true class been index 2 (with p2=0.1p_2 = 0.1), the loss would be −ln⁡(0.1)≈2.3026-\ln(0.1) \approx 2.3026, more than six times larger. A perfect py=1p_y = 1 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

Learn this in

More from CV: Recognition

solution.py

Test results

Sign in to run your code against the test cases.