Derive the Softmax Cross-Entropy Gradient and Implement It Stably

Last updated: November 29, 2026

Quick Overview

Derive the gradient of cross-entropy loss with respect to the logits of a softmax classifier, then implement the loss and gradient in a numerically stable way.

Amazon
Machine Learning
Machine Learning Engineer
Amazon
November 29, 2026
Machine Learning Engineer
Technical Screen
Machine Learning
Easy

0

0

0 solved


Derive the gradient of cross-entropy loss with respect to the logits of a softmax classifier, then implement the loss and gradient in a numerically stable way.

Amazon MLE screens frequently include a short derivation to make sure candidates understand what frameworks do under the hood, for example in a product category classifier. The interviewer checks the clean result $p-y$ and awareness of overflow.

What the Interviewer Expects
  • Write softmax and cross-entropy
  • Derive the gradient with respect to logits
  • Arrive at p minus one-hot
  • Implement with the max-shift or log-sum-exp trick
  • Verify with a numerical gradient check
Key Topics to Cover
Softmax
Cross-entropy
Gradients
Numerical stability
Log-sum-exp
How to Approach This
  1. Understand the bias-variance trade-off. High training accuracy but low test accuracy signals overfitting.
  2. Choose evaluation metrics carefully based on the problem. Accuracy alone is often insufficient.
  3. Feature engineering is often more impactful than model selection.
  4. Know when to use tree-based models (tabular data) vs neural networks (unstructured data).
  5. Handle class imbalance with SMOTE, class weights, or appropriate loss functions.
Possible Follow-up Questions
  • What is the gradient for a batch, and how do you average it?
  • How does label smoothing change the gradient?
  • Why do frameworks fuse softmax and cross-entropy into one op?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Explore ML Interview Prep
Sample Answer
Clarify

One example with logits z∈RKz\in\mathbb{R}^K and true class yy. Loss L=−log⁡pyL=-\log p_y with pk=ezk∑jezjp_k=\frac{e^{z_k}}{\sum_j e^{z_j}}....

Approach

Write L=−zy+log⁡∑jezjL=-z_y+\log\sum_j e^{z_j}. Differentiate: ∂L∂zk=−1[k=y]+ezk∑jezj=pk−1[k=y]\frac{\partial L}{\partial z_k}=-\mathbb{1}[k=y]+\frac{e^{z_k}}{\sum_j e^{z_j}}=p_k-\mathbb{1}[k=y]. So the gradient is p−onehot(y)p-\text{onehot}(y): push u...


Submit Your Answer
Markdown supported