v9.1.1
Menu

Apply Softmax for Predictions

easyPROModelingPyTorch ModelingPytorch

Problem Statement

Convert raw model outputs (logits) into probabilities using Softmax.

Background

Neural networks output raw scores called logits. To interpret these as probabilities, you need to apply Softmax, which converts them to values in [0, 1] that sum to 1 across classes.

Your Task

Write a function apply_softmax(logits) that takes a batch of logits and returns statistics about the resulting probability distribution.

Output Format

Return a dictionary with keys: "probabilities_sum" (list of floats, 1 decimal — should each be ~1.0), "predictions" (list of ints — predicted class per sample), "max_probs" (list of floats, 2 decimals — confidence per sample).

Example

Input
logits = [[2.0, 1.0, 0.1], [0.5, 2.5, 0.3]]
Output
{'probabilities_sum': [1.0, 1.0], 'predictions': [0, 1], 'max_probs': [0.66, 0.8]}
Reasoning
  • logits is a 2×32 \times 3 batch: each row is one sample and its 3 numbers are raw, unbounded class scores, not yet probabilities.
  • Each row is normalised on its own with pi=ezi∑jezjp_i = \frac{e^{z_i}}{\sum_j e^{z_j}}. Row 1: 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.21311.213, so p≈(0.659, 0.242, 0.099)p \approx (0.659,\ 0.242,\ 0.099).
  • Row 2: e0.5≈1.649e^{0.5} \approx 1.649, e2.5≈12.182e^{2.5} \approx 12.182, e0.3≈1.350e^{0.3} \approx 1.350, total 15.18115.181, so p≈(0.109, 0.802, 0.089)p \approx (0.109,\ 0.802,\ 0.089).
  • probabilities_sum: every row adds to exactly 1 by construction, so both give 1.0 at 1 decimal place.
  • predictions: the class (counting from 0) holding the largest probability in each row, giving [0, 1].
  • max_probs: those winning probabilities at 2 decimal places, 0.659→0.660.659 \to 0.66 and 0.802→0.800.802 \to 0.80, which prints as 0.8.
  • Notice the winner is always the class with the largest logit, because eze^z preserves order. Only the confidence depends on the gaps: row 2's lead of 2.02.0 yields 0.800.80, row 1's lead of 1.01.0 only 0.660.66.

Constraints

  • Use nn.Softmax(dim=1)
  • Round probabilities appropriately
  • Handle batch dimension correctly

Learn this in

More from Pytorch

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.