Softmax function

From testwiki
Jump to navigation Jump to search

Template:Short description Template:About Template:Redirect Template:Machine learning The softmax function, also known as softargmax[1]Template:Rp or normalized exponential function,[2]Template:Rp converts a vector of Template:Mvar real numbers into a probability distribution of Template:Mvar possible outcomes. It is a generalization of the logistic function to multiple dimensions, and is used in multinomial logistic regression. The softmax function is often used as the last activation function of a neural network to normalize the output of a network to a probability distribution over predicted output classes.

Definition

The softmax function takes as input a vector Template:Mvar of Template:Mvar real numbers, and normalizes it into a probability distribution consisting of Template:Mvar probabilities proportional to the exponentials of the input numbers. That is, prior to applying softmax, some vector components could be negative, or greater than one; and might not sum to 1; but after applying softmax, each component will be in the interval (0,1), and the components will add up to 1, so that they can be interpreted as probabilities. Furthermore, the larger input components will correspond to larger probabilities.

Formally, the standard (unit) softmax function σ:ℝK(0,1)K, where K>1, takes a vector 𝐳=(z1,,zK)ℝK and computes each component of vector σ(𝐳)(0,1)K with

σ(𝐳)i=ezij=1Kezj.

In words, the softmax applies the standard exponential function to each element zi of the input vector 𝐳 (consisting of K real numbers), and normalizes these values by dividing by the sum of all these exponentials. The normalization ensures that the sum of the components of the output vector σ(𝐳) is 1. The term "softmax" derives from the amplifying effects of the exponential on any maxima in the input vector. For example, the standard softmax of (1,2,8) is approximately (0.001,0.002,0.997), which amounts to assigning almost all of the total unit weight in the result to the position of the vector's maximal element (of 8).

In general, instead of Template:Mvar a different base Template:Math can be used. As above, if Template:Math then larger input components will result in larger output probabilities, and increasing the value of Template:Mvar will create probability distributions that are more concentrated around the positions of the largest input values. Conversely, if Template:Math then smaller input components will result in larger output probabilities, and decreasing the value of Template:Mvar will create probability distributions that are more concentrated around the positions of the smallest input values. Writing b=eβ or b=eβTemplate:Efn (for real Template:Mvar)Template:Efn yields the expressions:Template:Efn

σ(𝐳)i=eβzij=1Keβzj or σ(𝐳)i=eβzij=1Keβzj for i=1,,K.

Template:Anchor A value proportional to the reciprocal of Template:Mvar is sometimes referred to as the temperature: β=1/kT, where Template:Mvar is typically 1 or the Boltzmann constant and Template:Mvar is the temperature. A higher temperature results in a more uniform output distribution (i.e. with higher entropy; it is "more random"), while a lower temperature results in a sharper output distribution, with one value dominating.

In some fields, the base is fixed, corresponding to a fixed scale,Template:Efn while in others the parameter Template:Mvar (or Template:Mvar) is varied.

Interpretations

Smooth arg max

Template:See also The Softmax function is a smooth approximation to the arg max function: the function whose value is the index of a vector's largest element. The name "softmax" may be misleading. Softmax is not a smooth maximum (that is, a smooth approximation to the maximum function). The term "softmax" is also used for the closely related LogSumExp function, which is a smooth maximum. For this reason, some prefer the more accurate term "softargmax", though the term "softmax" is conventional in machine learning.[3]Template:Sfn This section uses the term "softargmax" for clarity.

Formally, instead of considering the arg max as a function with categorical output 1,,n (corresponding to the index), consider the arg max function with one-hot representation of the output (assuming there is a unique maximum arg): argmax(z1,,zn)=(y1,,yn)=(0,,0,1,0,,0), where the output coordinate yi=1 if and only if i is the arg max of (z1,,zn), meaning zi is the unique maximum value of (z1,,zn). For example, in this encoding argmax(1,5,10)=(0,0,1), since the third argument is the maximum.

This can be generalized to multiple arg max values (multiple equal zi being the maximum) by dividing the 1 between all max args; formally Template:Math where Template:Mvar is the number of arguments assuming the maximum. For example, argmax(1,5,5)=(0,1/2,1/2), since the second and third argument are both the maximum. In case all arguments are equal, this is simply argmax(z,,z)=(1/n,,1/n). Points Template:Mvar with multiple arg max values are singular points (or singularities, and form the singular set) – these are the points where arg max is discontinuous (with a jump discontinuity) – while points with a single arg max are known as non-singular or regular points.

With the last expression given in the introduction, softargmax is now a smooth approximation of arg max: as Template:Tmath, softargmax converges to arg max. There are various notions of convergence of a function; softargmax converges to arg max pointwise, meaning for each fixed input Template:Math as Template:Tmath, σβ(𝐳)argmax(𝐳). However, softargmax does not converge uniformly to arg max, meaning intuitively that different points converge at different rates, and may converge arbitrarily slowly. In fact, softargmax is continuous, but arg max is not continuous at the singular set where two coordinates are equal, while the uniform limit of continuous functions is continuous. The reason it fails to converge uniformly is that for inputs where two coordinates are almost equal (and one is the maximum), the arg max is the index of one or the other, so a small change in input yields a large change in output. For example, σβ(1,1.0001)(0,1), but σβ(1,0.9999)(1,0), and σβ(1,1)=1/2 for all inputs: the closer the points are to the singular set (x,x), the slower they converge. However, softargmax does converge compactly on the non-singular set.

Conversely, as Template:Tmath, softargmax converges to arg min in the same way, where here the singular set is points with two arg min values. In the language of tropical analysis, the softmax is a deformation or "quantization" of arg max and arg min, corresponding to using the log semiring instead of the max-plus semiring (respectively min-plus semiring), and recovering the arg max or arg min by taking the limit is called "tropicalization" or "dequantization".

It is also the case that, for any fixed Template:Mvar, if one input Template:Tmath is much larger than the others relative to the temperature, T=1/β, the output is approximately the arg max. For example, a difference of 10 is large relative to a temperature of 1: σ(0,10):=σ1(0,10)=(1/(1+e10),e10/(1+e10))(0.00005,0.99995) However, if the difference is small relative to the temperature, the value is not close to the arg max. For example, a difference of 10 is small relative to a temperature of 100: σ1/100(0,10)=(1/(1+e1/10),e1/10/(1+e1/10))(0.475,0.525). As Template:Tmath, temperature goes to zero, T=1/β0, so eventually all differences become large (relative to a shrinking temperature), which gives another interpretation for the limit behavior.

Statistical mechanics

In statistical mechanics, the softargmax function is known as the Boltzmann distribution (or Gibbs distribution):[4]Template:Rp the index set 1,,k are the microstates of the system; the inputs zi are the energies of that state; the denominator is known as the partition function, often denoted by Template:Mvar; and the factor Template:Mvar is called the coldness (or thermodynamic beta, or inverse temperature).

Applications

The softmax function is used in various multiclass classification methods, such as multinomial logistic regression (also known as softmax regression),[2]Template:Rp[5] multiclass linear discriminant analysis, naive Bayes classifiers, and artificial neural networks.[6] Specifically, in multinomial logistic regression and linear discriminant analysis, the input to the function is the result of Template:Mvar distinct linear functions, and the predicted probability for the Template:Mvarth class given a sample vector Template:Math and a weighting vector Template:Math is:

P(y=j𝐱)=e𝐱𝖳𝐰jk=1Ke𝐱𝖳𝐰k

This can be seen as the composition of Template:Mvar linear functions 𝐱𝐱𝖳𝐰1,,𝐱𝐱𝖳𝐰K and the softmax function (where 𝐱𝖳𝐰 denotes the inner product of 𝐱 and 𝐰). The operation is equivalent to applying a linear operator defined by 𝐰 to vectors 𝐱, thus transforming the original, probably highly-dimensional, input to vectors in a Template:Mvar-dimensional space ℝK.

Neural networks

The standard softmax function is often used in the final layer of a neural network-based classifier. Such networks are commonly trained under a log loss (or cross-entropy) regime, giving a non-linear variant of multinomial logistic regression.

Since the function maps a vector and a specific index i to a real value, the derivative needs to take the index into account:

qkσ(q,i)=σ(q,i)(δikσ(q,k)).

This expression is symmetrical in the indexes i,k and thus may also be expressed as

qkσ(q,i)=σ(q,k)(δikσ(q,i)).

Here, the Kronecker delta is used for simplicity (cf. the derivative of a sigmoid function, being expressed via the function itself).

To ensure stable numerical computations subtracting the maximum value from the input vector is common. This approach, while not altering the output or the derivative theoretically, enhances stability by directly controlling the maximum exponent value computed.

If the function is scaled with the parameter β, then these expressions must be multiplied by β.

See multinomial logit for a probability model which uses the softmax activation function.

Reinforcement learning

In the field of reinforcement learning, a softmax function can be used to convert values into action probabilities. The function commonly used is:[7] Pt(a)=exp(qt(a)/τ)i=1nexp(qt(i)/τ),

where the action value qt(a) corresponds to the expected reward of following action a and τ is called a temperature parameter (in allusion to statistical mechanics). For high temperatures (τ), all actions have nearly the same probability and the lower the temperature, the more expected rewards affect the probability. For a low temperature (τ0+), the probability of the action with the highest expected reward tends to 1.

Computational complexity and remedies

In neural network applications, the number Template:Mvar of possible outcomes is often large, e.g. in case of neural language models that predict the most likely outcome out of a vocabulary which might contain millions of possible words.[8] This can make the calculations for the softmax layer (i.e. the matrix multiplications to determine the zi, followed by the application of the softmax function itself) computationally expensive.[8][9] What's more, the gradient descent backpropagation method for training such a neural network involves calculating the softmax for every training example, and the number of training examples can also become large. The computational effort for the softmax became a major limiting factor in the development of larger neural language models, motivating various remedies to reduce training times.[8][9]

Approaches that reorganize the softmax layer for more efficient calculation include the hierarchical softmax and the differentiated softmax.[8] The hierarchical softmax (introduced by Morin and Bengio in 2005) uses a binary tree structure where the outcomes (vocabulary words) are the leaves and the intermediate nodes are suitably selected "classes" of outcomes, forming latent variables.[9][10] The desired probability (softmax value) of a leaf (outcome) can then be calculated as the product of the probabilities of all nodes on the path from the root to that leaf.[9] Ideally, when the tree is balanced, this would reduce the computational complexity from O(K) to O(log2K).[10] In practice, results depend on choosing a good strategy for clustering the outcomes into classes.[9][10] A Huffman tree was used for this in Google's word2vec models (introduced in 2013) to achieve scalability.[8]

A second kind of remedies is based on approximating the softmax (during training) with modified loss functions that avoid the calculation of the full normalization factor.[8] These include methods that restrict the normalization sum to a sample of outcomes (e.g. Importance Sampling, Target Sampling).[8][9]

Numerical algorithms

The standard softmax is numerically unstable because of large exponentiations. The safe softmax method calculates insteadσ(𝐳)i=eβ(zim)j=1Keβ(zjm)where m=maxizi is the largest factor involved. Subtracting by it guarantees that the exponentiations result in at most 1.

The attention mechanism in Transformers takes three arguments: a "query vector" q, a list of "key vectors" k1,,kN, and a list of "value vectors" v1,,vN, and outputs a softmax-weighted sum over value vectors:o=i=1NeqTkimj=1NeqTkjmviThe standard softmax method involves several loops over the inputs, which would be bottlenecked by memory bandwidth. The FlashAttention method is a communication-avoiding algorithm that fuses these operations into a single loop, increasing the arithmetic intensity. It is an online algorithm that computes the following quantities:[11][12]zi=qTkimi=max(z1,,zi)=max(mi1,zi)li=ez1mi++ezimi=emi1mili1+ezimioi=ez1miv1++ezimivi=emi1mioi1+ezimiviand returns oN/lN. In practice, FlashAttention operates over multiple queries and keys per loop iteration, in a similar way as blocked matrix multiplication. If backpropagation is needed, then the output vectors and the intermediate arrays [m1,,mN],[l1,,lN] are cached, and during the backward pass, attention matrices are rematerialized from these, making it a form of gradient checkpointing.

Mathematical properties

Geometrically the softmax function maps the vector space ℝK to the boundary of the standard (K1)-simplex, cutting the dimension by one (the range is a (K1)-dimensional simplex in K-dimensional space), due to the linear constraint that all output sum to 1 meaning it lies on a hyperplane.

Along the main diagonal (x,x,,x), softmax is just the uniform distribution on outputs, (1/n,,1/n): equal scores yield equal probabilities.

More generally, softmax is invariant under translation by the same value in each coordinate: adding 𝐜=(c,,c) to the inputs 𝐳 yields σ(𝐳+𝐜)=σ(𝐳), because it multiplies each exponent by the same factor, ec (because ezi+c=eziec), so the ratios do not change: σ(𝐳+𝐜)j=ezj+ck=1Kezk+c=ezjeck=1Kezkec=σ(𝐳)j.

Geometrically, softmax is constant along diagonals: this is the dimension that is eliminated, and corresponds to the softmax output being independent of a translation in the input scores (a choice of 0 score). One can normalize input scores by assuming that the sum is zero (subtract the average: 𝐜 where c=1nzi), and then the softmax takes the hyperplane of points that sum to zero, zi=0, to the open simplex of positive values that sum to 1σ(𝐳)i=1, analogously to how the exponent takes 0 to 1, e0=1 and is positive.

By contrast, softmax is not invariant under scaling. For instance, σ((0,1))=(1/(1+e),e/(1+e)) but σ((0,2))=(1/(1+e2),e2/(1+e2)).

The standard logistic function is the special case for a 1-dimensional axis in 2-dimensional space, say the x-axis in the Template:Math plane. One variable is fixed at 0 (say z2=0), so e0=1, and the other variable can vary, denote it z1=x, so ez1/k=12ezk=ex/(ex+1), the standard logistic function, and ez2/k=12ezk=1/(ex+1), its complement (meaning they add up to 1). The 1-dimensional input could alternatively be expressed as the line (x/2,x/2), with outputs ex/2/(ex/2+ex/2)=ex/(ex+1) and ex/2/(ex/2+ex/2)=1/(ex+1).

Gradients

The softmax function is also the gradient of the LogSumExp function:ziLSE(𝐳)=expzij=1Kexpzj=σ(𝐳)i, for i=1,,K,𝐳=(z1,,zK)ℝK,where the LogSumExp function is defined as LSE(z1,,zn)=log(exp(z1)++exp(zn)).

The gradient of softmax is thus zjσi=σi(δijσj).

History

The softmax function was used in statistical mechanics as the Boltzmann distribution in the foundational paper Template:Harvtxt,[13] formalized and popularized in the influential textbook Template:Harvtxt.[14]

The use of the softmax in decision theory is credited to R. Duncan Luce,[15]Template:Rp who used the axiom of independence of irrelevant alternatives in rational choice theory to deduce the softmax in Luce's choice axiom for relative preferences.Template:Cn

In machine learning, the term "softmax" is credited to John S. Bridle in two 1989 conference papers, Template:Harvtxt:[15]Template:Rp and Template:Harvtxt:[3] Template:Quote Template:Quote

Example

With an input of Template:Math, the softmax is approximately Template:Math. The output has most of its weight where the "4" was in the original input. This is what the function is normally used for: to highlight the largest values and suppress values which are significantly below the maximum value. But note: a change of temperature changes the output. When the temperature is multiplied by 10, the inputs are effectively Template:Math and the softmax is approximately Template:Math. This shows that high temperatures de-emphasize the maximum value.

Computation of this example using Python code:

>>> import numpy as np
>>> z = np.array([1.0, 2.0, 3.0, 4.0, 1.0, 2.0, 3.0])
>>> beta = 1.0
>>> np.exp(beta * z) / np.sum(np.exp(beta * z)) 
array([0.02364054, 0.06426166, 0.1746813, 0.474833, 0.02364054,
       0.06426166, 0.1746813])

Alternatives

The softmax function generates probability predictions densely distributed over its support. Other functions like sparsemax or Ξ±-entmax can be used when sparse probability predictions are desired.[16] Also the Gumbel-softmax reparametrization trick can be used when sampling from a discrete-discrete distribution needs to be mimicked in a differentiable manner.

See also

Notes

Template:Notelist

References

Template:Reflist

Template:Artificial intelligence navbox

  1. ↑ Template:Cite book
  2. ↑ 2.0 2.1 Template:Cite book
  3. ↑ 3.0 3.1 Cite error: Invalid <ref> tag; no text was provided for refs named sako2018
  4. ↑ Template:Cite book
  5. ↑ Template:Cite web
  6. ↑ ai-faq What is a softmax activation function?
  7. ↑ Sutton, R. S. and Barto A. G. Reinforcement Learning: An Introduction. The MIT Press, Cambridge, MA, 1998. Softmax Action Selection
  8. ↑ 8.0 8.1 8.2 8.3 8.4 8.5 8.6 Template:Cite journal
  9. ↑ 9.0 9.1 9.2 9.3 9.4 9.5 Template:Cite journal
  10. ↑ 10.0 10.1 10.2 Template:Cite journal
  11. ↑ Template:Citation
  12. ↑ Template:Cite journal
  13. ↑ Template:Cite journal
  14. ↑ Template:Cite book
  15. ↑ 15.0 15.1 Template:Cite arXiv
  16. ↑ "Speeding Up Entmax" by Maxat Tezekbayev, Vassilina Nikoulina, Matthias GallΓ©, Zhenisbek Assylbekov, https://arxiv.org/abs/2111.06832v3