Back to Practice
#0013

Stable Softmax

MediumML18 min15 XP

Problem

Given a one-dimensional NumPy array of logits, return softmax probabilities. Subtract the maximum logit before exponentiating.

Why This Matters

Softmax is used in multi-class classification, attention, and language models. The stable version prevents large logits from breaking the calculation.

Function Signature

def softmax(logits):

Examples

Example 1
Inputlogits = np.array([1.0, 2.0, 3.0])
Outputarray([0.09, 0.2447, 0.6652])

The largest logit gets the largest probability, but all probabilities sum to 1.

Constraints

  • Input is a one-dimensional numeric NumPy array.
  • Return probabilities that sum to 1.
  • Use max-shifting for numerical stability.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 4 hidden categories
Normal logits
Inputnp.array([1.0, 2.0, 3.0])
Expectedprobabilities sum to 1

Class 3 has the largest probability.

Large logits
Inputnp.array([1000.0, 1001.0])
Expectedfinite probabilities

Subtracting the max prevents exp(1001) overflow.

Hidden Test Categories
Equal logitsNegative logitsVery large logitsSingle dominant class