MLCrack

    ML MATH & LINEAR ALGEBRA ยท INTERVIEW QUESTION

    What is the softmax function? Walk through a numerical example.

    ๐ŸŸข beginner ยท Calculus & Optimization

    Hint: Exponentiate logits and normalize so they sum to 1.

    Answer

    Softmax converts raw logits into probabilities:

    P(yi)=eziโˆ‘j=1nezjP(y_i) = \frac{e^{z_i}}{\sum_{j=1}^{n} e^{z_j}}

    Properties: all probabilities โˆˆ[0,1]\in [0, 1] and โˆ‘P(yi)=1\sum P(y_i) = 1.

    Numerical Example

    Logits: z=[2.0,1.0,0.1]z = [2.0, 1.0, 0.1]

    1. Exponentiate: e2.0โ‰ˆ7.39e^{2.0} \approx 7.39, e1.0โ‰ˆ2.72e^{1.0} \approx 2.72, e0.1โ‰ˆ1.11e^{0.1} \approx 1.11
    2. Sum: 7.39+2.72+1.11=11.227.39 + 2.72 + 1.11 = 11.22
    3. Normalize: P1=7.39/11.22โ‰ˆ0.66P_1 = 7.39/11.22 \approx 0.66, P2โ‰ˆ0.24P_2 \approx 0.24, P3โ‰ˆ0.10P_3 \approx 0.10

    Result: [0.66,0.24,0.10][0.66, 0.24, 0.10] โ€” model assigns ~66% to class 1.

    python
    import numpy as np def softmax(z, temperature=1.0): z = np.array(z) / temperature exp_z = np.exp(z - np.max(z)) # subtract max for stability return exp_z / exp_z.sum() logits = [2.0, 1.0, 0.1] print('Softmax:', softmax(logits)) # [0.659, 0.242, 0.099] print('T=0.5:', softmax(logits, 0.5)) # sharper print('T=2.0:', softmax(logits, 2.0)) # more uniform

    Temperature scaling: softmax(z/T)\text{softmax}(z/T) โ€” higher TT โ†’ uniform, lower TT โ†’ sharper.

    Likely follow-up: What happens to softmax outputs as temperature approaches 0 vs infinity?