All formulas

Machine learning building blocks

Softmax

ml.softmaxAlso called softmax, soft max, normalized exponential, softargmax

softmax⁡(x)i=exi∑j=1nexj\operatorname{softmax}(x)_i = \frac{e^{x_i}}{\sum_{j=1}^{n} e^{x_j}}

Turns a vector of scores into a probability vector. Adding a constant to every score leaves the result unchanged, which is what lets stable implementations subtract the maximum first.

Notation

xx

logits (unnormalized scores)

x ∈ ℝn

nn

number of entries

Size, at least 2

softmax⁡(x)\operatorname{softmax}(x)

Result: the probabilities

vector

Worked examples

Each result is solved exactly and confirmed by two independent computations.

  1. Given

    x=[0,0]x = [0, 0]

    Result

    softmax⁡(x)=(12,12)\displaystyle \operatorname{softmax}(x) = \left(\frac{1}{2}, \frac{1}{2}\right)

    ≈ (0.5, 0.5)

  2. Given

    x=[1,2,3]x = [1, 2, 3]

    Result

    softmax⁡(x)=(ee+e2+e3,e2e+e2+e3,e3e+e2+e3)\displaystyle \operatorname{softmax}(x) = \left(\frac{e}{e + e^{2} + e^{3}}, \frac{e^{2}}{e + e^{2} + e^{3}}, \frac{e^{3}}{e + e^{2} + e^{3}}\right)

    ≈ (0.0900305731704, 0.244728471055, 0.665240955775)

  3. Given

    x=[1000,1000,1000]x = [1000, 1000, 1000]

    Result

    softmax⁡(x)=(13,13,13)\displaystyle \operatorname{softmax}(x) = \left(\frac{1}{3}, \frac{1}{3}, \frac{1}{3}\right)

    ≈ (0.333333333333, 0.333333333333, 0.333333333333)

Common mistakes

  • Exponentiates without subtracting the maximum

    exp overflows to inf for scores above about 709 (and every term underflows to 0 below about −745), so the result is NaN.

    Fix: Subtract the maximum score before exponentiating, or call scipy.special.softmax / torch.softmax.

  • Does not divide by the sum

    The exponentials are returned without normalizing, so they do not sum to one.

    Fix: Divide each exponential by the sum of all of them.

Sources

  • Goodfellow et al. 2016, §6.2.2.3

    Goodfellow, Ian; Bengio, Yoshua; Courville, Aaron. Deep Learning. MIT Press, 2016.

    deeplearningbook.org
  • Bridle 1990

    Bridle, John S. Probabilistic Interpretation of Feedforward Classification Network Outputs, with Relationships to Statistical Pattern Recognition. In Neurocomputing: Algorithms, Architectures and Applications, pp. 227-236, 1990. doi:10.1007/978-3-642-76153-9_28

    doi.org