Categorical Cross-Entropy

MediumMachine LearningMath

Description

Given a predicted probability distribution over classes and the index of the true class, return the categorical cross-entropy loss for that example: the negative natural log of the predicted probability of the true class. Round the result to 4 decimal places.

Examples

Input:[0.7,0.2,0.1], 0
Output:0.3567
Explanation:

The loss is the negative log of the probability the model assigned to the correct class, so confident correct predictions cost little.

Input:[0.1,0.8,0.1], 1
Output:0.2231
Explanation:

The loss is the negative log of the probability the model assigned to the correct class, so confident correct predictions cost little.

Input:[0.25,0.25,0.25,0.25], 2
Output:1.3863
Explanation:

The loss is the negative log of the probability the model assigned to the correct class, so confident correct predictions cost little.

Constraints

  • 1 ≤ classes ≤ 10³
  • probabilities sum to 1

Ready to solve this problem?

Practice solo and sharpen your skills for technical interviews.