v9.1.1
Menu

Softmax Function

mediumFREEClassificationMachine Learning 1

Implement the softmax function for multi-class classification.

Given a list of logits (raw scores) z=[z1,z2,...,zk]z = [z_1, z_2, ..., z_k], compute the softmax probabilities:

softmax(zi)=ezi∑j=1kezj\text{softmax}(z_i) = \frac{e^{z_i}}{\sum_{j=1}^{k} e^{z_j}}

For numerical stability, subtract the maximum value from all logits before exponentiating: softmax(zi)=ezi−max⁡(z)∑j=1kezj−max⁡(z)\text{softmax}(z_i) = \frac{e^{z_i - \max(z)}}{\sum_{j=1}^{k} e^{z_j - \max(z)}}

Return the probability distribution as a list, rounded to 4 decimal places.

Example

Input
logits = [2.0, 1.0, 0.1]
Output
[0.6590, 0.2424, 0.0986]
Reasoning
  • logits holds one raw score per class, z=[2.0,1.0,0.1]z = [2.0, 1.0, 0.1]. Scores can be any real numbers, so they are not probabilities yet.
  • Exponentiating makes every score positive: e2.0≈7.389e^{2.0} \approx 7.389, e1.0≈2.718e^{1.0} \approx 2.718, e0.1≈1.105e^{0.1} \approx 1.105, total ≈11.213\approx 11.213. Dividing each by the total gives 7.389/11.213≈0.65907.389 / 11.213 \approx 0.6590, and so on.
  • The stability trick shifts every logit by the largest one, 2.02.0, giving [0.0,−1.0,−1.9][0.0, -1.0, -1.9] and exponentials [1,0.3679,0.1496][1, 0.3679, 0.1496] with total 1.51741.5174. Each term was scaled by the same factor e−2e^{-2}, so the ratios are unchanged: 1/1.5174≈0.65901 / 1.5174 \approx 0.6590, 0.3679/1.5174≈0.24240.3679 / 1.5174 \approx 0.2424, 0.1496/1.5174≈0.09860.1496 / 1.5174 \approx 0.0986.
  • The output [0.6590, 0.2424, 0.0986] has one probability per logit, in the same order, rounded to 4 decimal places, and they sum to 11.
  • Notice that a logit gap of 1.01.0 multiplies the probability by e≈2.72e \approx 2.72 (0.6590/0.2424≈2.720.6590 / 0.2424 \approx 2.72). Equal logits such as [100,100,100][100, 100, 100] all shift to 00, so each gets 1/31/3; for logits near 10001000, e1000e^{1000} would overflow without the shift.

Constraints

  • Input is a list of floats (logits)
  • Return a list of probabilities that sum to 1 (approximately)
  • Round each value to 4 decimal places
  • Use the numerical stability trick (subtract max)

Learn this in

More from Machine Learning 1

solution.py

Test results

Sign in to run your code against the test cases.