Machine learning building blocks
Softmax
ml.softmaxAlso called softmax, soft max, normalized exponential, softargmax
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
logits (unnormalized scores)
x ∈ ℝn
number of entries
Size, at least 2
Result: the probabilities
vector
Worked examples
Each result is solved exactly and confirmed by two independent computations.
Given
Result
≈ (0.5, 0.5)
Given
Result
≈ (0.0900305731704, 0.244728471055, 0.665240955775)
Given
Result
≈ (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.
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