MLCrack

    ML MATH & LINEAR ALGEBRA Β· INTERVIEW QUESTION

    Derive the gradient of the cross-entropy loss for softmax output.

    πŸ”΄ advanced Β· Calculus & Optimization

    Hint: Start with the softmax function, write the cross-entropy loss, and use the quotient rule.

    Answer

    Softmax function:

    pi=eziβˆ‘jezjp_i = \frac{e^{z_i}}{\sum_j e^{z_j}}

    Cross-entropy loss:

    L=βˆ’βˆ‘iyilog⁑(pi)\mathcal{L} = -\sum_i y_i \log(p_i)

    The gradient has an elegant form:

    βˆ‚Lβˆ‚zi=piβˆ’yi\frac{\partial \mathcal{L}}{\partial z_i} = p_i - y_i

    This comes from the Jacobian of softmax:

    βˆ‚piβˆ‚zj=pi(Ξ΄ijβˆ’pj)\frac{\partial p_i}{\partial z_j} = p_i(\delta_{ij} - p_j)

    where Ξ΄ij\delta_{ij} is the Kronecker delta. Substituting into the chain rule and using βˆ‘yi=1\sum y_i = 1 gives the compact form.

    This is why softmax + cross-entropy is preferred: the gradient is simply the difference between predicted and true probabilities.

    python
    import numpy as np def softmax(z): exp_z = np.exp(z - np.max(z)) # numerical stability return exp_z / exp_z.sum() def cross_entropy_grad(z, y_true): p = softmax(z) return p - y_true # elegant!