Implement Cross-Entropy Loss
Implement Cross-Entropy Loss
Compute the average cross-entropy loss for multi-class classification.
y_true contains the correct class labels (like [0, 2, 1])
y_pred contains the predicted probabilities for each class (each row sums to ~1)
For each sample, the loss is:
lossi=−log(pi,yi)Where:
yi=correct class label for sample i
pi,yi=predicted probability for that class
The final cross-entropy loss is the average:
CrossEntropy=−N1i=1∑Nlog(pi,yi)Note: You can assume all probabilities are valid (greater than 0), so no need to worry about log(0) .
Examples
Input: y_true = [0, 1], y_pred = [[0.9, 0.1], [0.3, 0.7]]
Output: 0.231018
Input: y_true = [2], y_pred = [[0.1, 0.1, 0.8]]
Output: 0.223144
Input: y_true = [1, 0, 1], y_pred = [[0.2, 0.8], [0.6, 0.4], [0.49, 0.51]]
Output: 0.469105
Hint 1
Use np.arrange() with advanced indexing to extract probabilities for the correct classes.
Hint 2
Use np.log() and np.mean() to compute the negative average of logarithms.
Requirements
- y_true and y_pred must have matching first dimension N
- y_true contains valid class indices for the second dimension of y_pred
- Vectorized (no Python loops over samples)
- Input is probabilities (not logits)
- All probabilities are guaranteed to be > 0
Constraints
- 1 ≤ N ≤ 105, 2 ≤ K ≤ 100
- ∑k pi,k ≈ 1 for each row
- NumPy only; time limit: 200 ms
Try Similar Problems
Log in to take notes on this problem
Accepts: array
Accepts: array
Implement Cross-Entropy Loss
Implement Cross-Entropy Loss
Compute the average cross-entropy loss for multi-class classification.
y_true contains the correct class labels (like [0, 2, 1])
y_pred contains the predicted probabilities for each class (each row sums to ~1)
For each sample, the loss is:
lossi=−log(pi,yi)Where:
yi=correct class label for sample i
pi,yi=predicted probability for that class
The final cross-entropy loss is the average:
CrossEntropy=−N1i=1∑Nlog(pi,yi)Note: You can assume all probabilities are valid (greater than 0), so no need to worry about log(0) .
Examples
Input: y_true = [0, 1], y_pred = [[0.9, 0.1], [0.3, 0.7]]
Output: 0.231018
Input: y_true = [2], y_pred = [[0.1, 0.1, 0.8]]
Output: 0.223144
Input: y_true = [1, 0, 1], y_pred = [[0.2, 0.8], [0.6, 0.4], [0.49, 0.51]]
Output: 0.469105
Hint 1
Use np.arrange() with advanced indexing to extract probabilities for the correct classes.
Hint 2
Use np.log() and np.mean() to compute the negative average of logarithms.
Requirements
- y_true and y_pred must have matching first dimension N
- y_true contains valid class indices for the second dimension of y_pred
- Vectorized (no Python loops over samples)
- Input is probabilities (not logits)
- All probabilities are guaranteed to be > 0
Constraints
- 1 ≤ N ≤ 105, 2 ≤ K ≤ 100
- ∑k pi,k ≈ 1 for each row
- NumPy only; time limit: 200 ms
Try Similar Problems
Log in to take notes on this problem
Accepts: array
Accepts: array