Search

Search papers and lessons

Sparsemax

Level 4 · 10 min read

Sparsemax turns a list of scores into probabilities like softmax does, but it can give some entries exactly zero, by projecting the scores onto the probability simplex.

On this page

  • Colour = topic mix
  • Linear algebra
  • Discrete math
  • Calculus
  • Neural network basics
  • Probability
  • ReadReady to readNot yet

TL;DR

Sparsemax is a function that takes a vector of real scores and returns a vector of probabilities, the same kind of output that Softmax gives. The difference is that sparsemax can return exact zeros, so a few entries get all the probability and the rest get none. It does this by finding the point closest to the scores among all probability vectors, which is a projection onto the probability simplex.

Builds on: Softmax, Orthogonal Projection · Leads to: TabNet: Attentive Interpretable Tabular Learning

Where it's used

Attention with a clear choice. In attention layers of a Transformer, a model scores each input position and turns the scores into weights. With softmax every position gets some weight, however small. With sparsemax the weights can be exactly zero, so the model reads only a few positions and the choice is easy to inspect.

Multi-label classification. Softmax assumes one correct class. A logistic output per label allows several labels, but gives no shared distribution. When several labels can be true at once, sparsemax lets the model assign probability only to the labels that matter. The paper that introduced sparsemax covers this use alongside attention.

Feature selection in tabular models. The TabNet architecture (see the TabNet paper) learns a sparse mask over the input features at each decision step, so each step uses only a few features. The mask is built from the same family of ideas: normalise scores into a probability-like vector and let most entries drop to zero.

How it works

Take a three-entry score vector z=(1.0, 0.5, −1.0)z = (1.0,\ 0.5,\ -1.0). Here is what sparsemax does with it.

  1. Sort the scores from largest to smallest. The sorted vector is (1.0, 0.5, −1.0)(1.0,\ 0.5,\ -1.0). Call the sorted entries z(1)≥z(2)≥z(3)z_{(1)} \ge z_{(2)} \ge z_{(3)}. Check: the largest score is first, and the order is the only thing sorting changes.
  2. Find how many entries stay positive. For each kk, test whether 1+k⋅z(k)1 + k \cdot z_{(k)} is greater than the sum of the first kk sorted scores. Keep the largest kk that passes.
    • k=1k = 1: 1+1⋅1.0=2.01 + 1 \cdot 1.0 = 2.0 against 1.01.0. Passes.
    • k=2k = 2: 1+2⋅0.5=2.01 + 2 \cdot 0.5 = 2.0 against 1.0+0.5=1.51.0 + 0.5 = 1.5. Passes.
    • k=3k = 3: 1+3⋅(−1.0)=−2.01 + 3 \cdot (-1.0) = -2.0 against 0.50.5. Fails. So k=2k = 2. Check: the test fails once a score is too small to keep, so the count stops growing.
  3. Compute a threshold. Set τ=1.0+0.5−12=0.25\tau = \dfrac{1.0 + 0.5 - 1}{2} = 0.25. This is the amount that each kept score is lowered by, chosen so the result sums to one. Check: τ\tau is the average excess of the kept scores over 1.
  4. Subtract the threshold and clip at zero. Each output is max⁡(zi−τ, 0)\max(z_i - \tau,\ 0). That gives (1.0−0.25, 0.5−0.25, −1.0−0.25 clipped to 0)=(0.75, 0.25, 0)(1.0 - 0.25,\ 0.5 - 0.25,\ -1.0 - 0.25 \text{ clipped to } 0) = (0.75,\ 0.25,\ 0). Check: the entries are non-negative and add to 0.75+0.25+0=10.75 + 0.25 + 0 = 1.
  5. Compare with softmax. Softmax on the same scores gives about (0.574, 0.348, 0.078)(0.574,\ 0.348,\ 0.078). Every entry is positive. Sparsemax gives the third entry exactly zero. Check: both outputs sum to one, and only sparsemax has a true zero.
flowchart LR
  Z["Scores z"] --> S[Sort descending]
  S --> K["Find largest k that passes the test"]
  K --> T["Threshold tau from the first k scores"]
  T --> C["Output max of z minus tau, and 0"]
  C --> P["Probabilities with exact zeros"]

The math

Definition: Sparsemax

For a score vector z∈Rnz \in \mathbb{R}^n, sparsemax is the point of the probability simplex closest to zz in Euclidean distance: sparsemax⁡(z)=arg⁡min⁡p∈Δn  ∥p−z∥2,\operatorname{sparsemax}(z) = \arg\min_{p \in \Delta^{n}} \; \lVert p - z \rVert^2, where Δn={p∈Rn:pi≥0, ∑ipi=1}\Delta^{n} = \{ p \in \mathbb{R}^n : p_i \ge 0,\ \sum_i p_i = 1 \} is the set of probability vectors with nn entries. The solution has the closed form given below.

Step 1 in symbols: sorting

Write the sorted scores as z(1)≥z(2)≥⋯≥z(n)z_{(1)} \ge z_{(2)} \ge \dots \ge z_{(n)}. Sorting does not change the answer; it only makes the test below easy to run.

Step 2 in symbols: the support size

Let k(z)=max⁡{k∈{1,…,n}:1+k z(k)>∑j=1kz(j)}.k(z) = \max\left\{ k \in \{1, \dots, n\} : 1 + k \, z_{(k)} > \sum_{j=1}^{k} z_{(j)} \right\}. The set of the first k(z)k(z) sorted entries is the support, the entries that stay positive. For the example z=(1.0, 0.5, −1.0)z = (1.0,\ 0.5,\ -1.0) the test passes for k=1k = 1 and k=2k = 2 and fails for k=3k = 3, so k(z)=2k(z) = 2.

Step 3 in symbols: the threshold

τ(z)=1k(z)(∑j=1k(z)z(j)−1).\tau(z) = \frac{1}{k(z)} \left( \sum_{j=1}^{k(z)} z_{(j)} - 1 \right). For the example, τ=(1.0+0.5−1)/2=0.25\tau = (1.0 + 0.5 - 1) / 2 = 0.25.

Step 4 in symbols: the output

sparsemax⁡i(z)=max⁡(zi−τ(z), 0).\operatorname{sparsemax}_i(z) = \max\left( z_i - \tau(z),\ 0 \right). The output is zero exactly when zi≤τ(z)z_i \le \tau(z). For the example this gives (0.75, 0.25, 0)(0.75,\ 0.25,\ 0).

Comparison with softmax

Softmax is softmax⁡i(z)=ezi/∑jezj\operatorname{softmax}_i(z) = e^{z_i} / \sum_j e^{z_j}, built from the Exponential Function, which is strictly positive for every entry. The two functions share the same output space, the probability simplex Δn\Delta^{n}. They differ in the map: softmax is smooth and never zero, while sparsemax is piecewise linear and can be exactly zero. The clip at zero in step 4 is the same operation as a ReLU. The Gradient of softmax is dense; the Gradient of sparsemax is zero for entries outside the support. That is the price of sparsity: no signal flows through the entries that were set to zero.

Worked examples

Example
Two scores

Take z=(1, 0)z = (1,\ 0).

  1. Sorted: z(1)=1z_{(1)} = 1, z(2)=0z_{(2)} = 0.
  2. For k=1k = 1: 1+1⋅1=2>11 + 1 \cdot 1 = 2 > 1. Passes.
  3. For k=2k = 2: 1+2⋅0=11 + 2 \cdot 0 = 1 against 1+0=11 + 0 = 1. The test needs strictly greater, so it fails.
  4. So k=1k = 1, and τ=(1−1)/1=0\tau = (1 - 1) / 1 = 0.
  5. Output: max⁡(1−0, 0)=1\max(1 - 0,\ 0) = 1 and max⁡(0−0, 0)=0\max(0 - 0,\ 0) = 0, so p=(1, 0)p = (1,\ 0).

Interpretation: when one score is larger than the other by 1, sparsemax puts all probability on it. Softmax would put e/(e+1)≈0.731e / (e + 1) \approx 0.731 on the first entry, using the Exponential Function of each score.

Example
The three-score vector from the walkthrough

Take z=(1.0, 0.5, −1.0)z = (1.0,\ 0.5,\ -1.0), as in "How it works".

  1. The support has k=2k = 2 entries, found in the second step of the walkthrough.
  2. Threshold: τ=(1.0+0.5−1)/2=0.25\tau = (1.0 + 0.5 - 1) / 2 = 0.25.
  3. Subtract and clip: (1.0−0.25, 0.5−0.25, max⁡(−1.0−0.25,0))=(0.75, 0.25, 0)(1.0 - 0.25,\ 0.5 - 0.25,\ \max(-1.0 - 0.25, 0)) = (0.75,\ 0.25,\ 0).
  4. Sum check: 0.75+0.25+0=10.75 + 0.25 + 0 = 1.

Interpretation: the third score is far below the others, so it falls below the threshold and gets no probability at all. Softmax would still give it 0.0780.078.

Example
Choosing attention positions

A model scores four input positions with z=(2.0, 1.8, 0.2, −0.5)z = (2.0,\ 1.8,\ 0.2,\ -0.5).

  1. Sorted: 2.0, 1.8, 0.2, −0.52.0,\ 1.8,\ 0.2,\ -0.5.
  2. For k=1k = 1: 1+2.0=3.0>2.01 + 2.0 = 3.0 > 2.0. Passes.
  3. For k=2k = 2: 1+2⋅1.8=4.6>2.0+1.8=3.81 + 2 \cdot 1.8 = 4.6 > 2.0 + 1.8 = 3.8. Passes.
  4. For k=3k = 3: 1+3⋅0.2=1.6>2.0+1.8+0.2=4.01 + 3 \cdot 0.2 = 1.6 > 2.0 + 1.8 + 0.2 = 4.0? No. Fails.
  5. So k=2k = 2, and τ=(3.8−1)/2=1.4\tau = (3.8 - 1) / 2 = 1.4.
  6. Output: (2.0−1.4, 1.8−1.4, 0.2−1.4 clipped, −0.5−1.4 clipped)=(0.6, 0.4, 0, 0)(2.0 - 1.4,\ 1.8 - 1.4,\ 0.2 - 1.4 \text{ clipped},\ -0.5 - 1.4 \text{ clipped}) = (0.6,\ 0.4,\ 0,\ 0).

Interpretation: the model reads exactly two of the four positions, and the weights 0.6 and 0.4 say how much each one counts. Softmax would spread weight over all four and make the choice harder to read.

Try it: for z=(0.9, 0.3, 0.2)z = (0.9,\ 0.3,\ 0.2), which entries of the output are nonzero, and what are they? Answer: all three are nonzero. Here k=3k = 3 because 1+3⋅0.2=1.6>1.41 + 3 \cdot 0.2 = 1.6 > 1.4, so τ=(1.4−1)/3≈0.133\tau = (1.4 - 1) / 3 \approx 0.133, and the output is (0.767, 0.167, 0.067)(0.767,\ 0.167,\ 0.067).

Common mistakes and tradeoffs

It is tempting to think sparsemax is always sparser in practice, so it can replace softmax anywhere. In fact the number of zeros depends on the spread of the scores. When the scores are close together, the support is large and sparsemax behaves much like softmax. The zeros appear only when a few scores clearly stand out.

It is tempting to think a zero in the output means the entry was irrelevant to training. In fact the gradient is zero for entries outside the support, so those entries receive no learning signal in that step, while the entries inside it receive a dense one. Check that the scores can still move into the support under gradient descent, or the model may stop using some positions.

It is tempting to think the exact zeros make the model easier to explain. They help, because the reader can see which positions were used. But the zeros depend on the score threshold, and a small change in scores can move an entry across it.

When to use sparsemax: when a few options should carry all the weight, when several labels can be true together, or when a sparse selection is part of the design. When not to use it: when every option should keep some weight, or when the training signal must flow to all entries. The usual alternative is softmax, which is smooth and dense. Sparse selection is also familiar from lasso regression, which sets some weights exactly to zero. A middle path is the alpha-entmax family, which interpolates between softmax and sparsemax.

History

Softmax was the standard way to turn scores into probabilities for classification and attention. Its outputs are never zero, which made it hard to tell which inputs really mattered. In 2016 André Martins and Ramón Fernandez Astudillo proposed sparsemax as a drop-in map with the same output space and exact zeros, and showed it on attention and on multi-label classification. The idea caught on because the sparse weights are easy to read and cheap to compute, since the threshold comes from a sort and a single pass.

Recap

  • Softmax turns scores into probabilities that are always positive. Sparsemax turns them into probabilities that can be exactly zero.
  • Sparsemax is the Euclidean projection of the scores onto the probability simplex, so its output is the closest valid probability vector.
  • Its computation is a sort, a search for the support size kk, and a threshold τ\tau that is subtracted from the scores.
  • The zeros make attention and multi-label outputs easier to read, and they remove gradient from the entries outside the support.
  • Read next: Attention Mechanism for where the weights are used, and TabNet for a sparse feature mask.

Check yourself

QuestionIn one sentence, what extra property does sparsemax have that softmax does not?Show answer

Sparsemax can output exact zeros, so some entries get no probability at all, while softmax gives every entry a positive value.

QuestionFor the scores z=(2, 0, −1)z = (2,\ 0,\ -1), what is the output of sparsemax?Show answer

Sorted: 2,0,−12, 0, -1. For k=1k = 1: 1+2=3>21 + 2 = 3 > 2, passes. For k=2k = 2: 1+0=1>2+0=21 + 0 = 1 > 2 + 0 = 2? No, fails. So k=1k = 1 and τ=2−1=1\tau = 2 - 1 = 1. Output: max⁡(2−1,0)=1\max(2 - 1, 0) = 1, max⁡(0−1,0)=0\max(0 - 1, 0) = 0, max⁡(−1−1,0)=0\max(-1 - 1, 0) = 0. So the output is (1, 0, 0)(1,\ 0,\ 0).

QuestionWhy might a model with sparsemax attention be easier to inspect than one with softmax attention, and what is a risk of relying on the zeros?Show answer

With sparsemax, the entries that get no weight are visibly absent, so the reader sees which positions were used. The risk is that the zeros depend on a threshold, so small changes in the scores can move an entry across it and change which positions are used, and entries outside the support get no gradient in that step.

QuestionA classifier must label each image with any subset of ten tags, and the tags are not exclusive. Why might sparsemax suit this better than softmax?Show answer

Softmax forces one probability distribution that assumes one correct class, so it spreads mass across tags even when only two apply. Sparsemax can give probability exactly zero to the tags that do not apply, so the output reflects a set of active tags more directly. This is the multi-label use described in the paper that introduced it.

Sources