Implement Cross-Entropy Loss
Updated
Problem statement
You are given a batch of model probability distributions probabilities and the correct class index for each example in labels.
Return the mean multiclass cross-entropy loss:
-(1 / n) * sum(log(probabilities[i][labels[i]])).
Use the natural logarithm.
Function
crossEntropyLoss(probabilities: double[][], labels: int[]) → doubleExamples
Example 1
probabilities = [[0.7,0.2,0.1],[0.1,0.5,0.4]]labels = [0,2]return = 0.6364828379The mean loss is (-log(0.7) - log(0.4)) / 2.
Example 2
probabilities = [[1.0,0.0],[0.0,1.0]]labels = [0,1]return = 0.0Both correct classes have probability 1, so both negative log terms are 0.
Constraints
1 <= probabilities.length == labels.length <= 10^4.- Every probability row has the same length from
2through1000. - Each row contains finite values in
[0, 1]whose sum differs from1by at most10^-9. 0 <= labels[i] < probabilities[i].length, and every correct-class probability is strictly positive.
More OpenAI Phone Screen questions
- Secret Number Search with One-Call-Delayed FeedbackPHONE SCREEN · Seen Nov 2026
- Determine the Winner of Three-Card HandsPHONE SCREEN · Seen Nov 2026
- Grid Infection with Recovery After D DaysPHONE SCREEN · Seen Nov 2026
- Sparse Plant Infection SimulationPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Light Source Hits: Sample, Compare, and FitPHONE SCREEN · Seen Nov 2026
- Rectangle Point Coverage CountsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Adaptive Calibration ErrorPHONE SCREEN · Seen Nov 2026
- Elevator Scheduling SimulationPHONE SCREEN · Seen Nov 2026
- Evaluate Noisy AnnotatorsPHONE SCREEN · Seen Oct 2026
- Network Endpoint or Cycle BoundaryOA · PHONE SCREEN · Seen Oct 2026
Similar questions at other companies
- Vanilla RNN Hidden StatesNVIDIA · PHONE SCREENNVIDIA interview questions
- Scaled Dot-Product AttentionAmazon · PHONE SCREEN
- Transformer Attention and SwiGLU Forward PassGoogle · ONSITE INTERVIEWGoogle interview questions
- Constant-Time Weighted Pick with an Alias TableEtched · PHONE SCREEN
- Apply a 2048 Board MoveGlean · PHONE SCREENGlean interview questions
- Spiral Order with ObstaclesTemu · PHONE SCREENTemu interview questions
- Logistic Regression DiagnosticsLinkedIn · PHONE SCREENLinkedIn interview questions
- Spiral Matrix TraversalByteDance · PHONE SCREENByteDance interview questions
- S-Shaped Matrix TraversalFox Corporation · PHONE SCREEN
- Process Minesweeper Game OperationsAmperity · PHONE SCREENAmperity interview questions