v9.1.1
Menu

Softmax

mediumFREENeural NetworksDeep LearningCV: Deep Learning

Implement the softmax function, a crucial component in neural networks that converts logits to probabilities. This process is essential for making predictions in classification problems.

The softmax function takes a vector of real numbers as input and outputs a vector of values in the range (0, 1) that add up to 1, making it suitable for representing a probability distribution. The softmax function is often used in the output layer of a neural network to ensure that the output values can be interpreted as probabilities.

To apply the softmax function, the following steps are involved:

  1. Exponentiate each input value,
  2. Calculate the sum of these exponentiated values,
  3. Divide each exponentiated value by the sum.
softmax(xi)=exi∑jexj\text{softmax}(x_i) = \frac{e^{x_i}}{\sum_j e^{x_j}}

This technique is widely used in image classification and natural language processing tasks.

Example

Input
softmax([1, 2, 3])
Output
[0.0900, 0.2447, 0.6652]
Reasoning
  • Input: x is a list of logits, raw scores for three classes: 11, 22, 33. They can be any real numbers, including negatives, and they don't sum to anything in particular.
  • Numerators: raise ee to each logit: e1≈2.7183e^1 \approx 2.7183, e2≈7.3891e^2 \approx 7.3891, e3≈20.0855e^3 \approx 20.0855. Every term is now positive, and larger logits get disproportionately larger weights.
  • Normaliser: the denominator ∑jexj≈2.7183+7.3891+20.0855=30.1929\sum_j e^{x_j} \approx 2.7183 + 7.3891 + 20.0855 = 30.1929 is shared by every output.
  • Output: 2.718330.1929≈0.0900\frac{2.7183}{30.1929} \approx 0.0900, 7.389130.1929≈0.2447\frac{7.3891}{30.1929} \approx 0.2447, 20.085530.1929≈0.6652\frac{20.0855}{30.1929} \approx 0.6652. Each value is rounded to 4 decimal places, giving [0.0900, 0.2447, 0.6652]. The three values sum to 11, so they form a probability distribution, and the largest logit gets the largest probability.
  • Notice: neighbouring logits differ by 11, so each probability is e≈2.718e \approx 2.718 times the one before it (0.2447/0.0900≈2.720.2447 / 0.0900 \approx 2.72). Only the differences between logits decide the ratios.

Constraints

  • Return probabilities rounded to 4 decimal places

Learn this in

More from CV: Deep Learning

solution.py

Test results

Sign in to run your code against the test cases.