Stable softmax and cross-entropy
Problem
A classifier gives one row of logits for each example. Softmax turns each row into probabilities. Cross-entropy measures how much probability the model gives to the correct class. Its gradient with respect to the logits is the signal that trains every classifier in the course.
Task
Write three functions.
softmax(logits)returns the softmax of each row.cross_entropy(logits, targets)returns the mean cross-entropy loss over the batch.cross_entropy_grad(logits, targets)returns the gradient of that mean loss with respect tologits.
The softmax of a row z is p_i = e^{z_i} / \sum_j e^{z_j}. The loss of one example with the correct class y is -\log p_y. The batch loss is the mean of the example losses.
Large logits overflow np.exp. Your softmax must give correct probabilities for logits such as 1000.0.
Input and output
| Name | Type | Shape | Meaning |
|---|---|---|---|
logits | float array | (N, C) | one row of scores for each of the N examples, C classes |
targets | int array | (N,) | the correct class of each example, from 0 to C - 1 |
softmaxreturns a float array of shape(N, C).cross_entropyreturns a Pythonfloat.cross_entropy_gradreturns a float array of shape(N, C).
Constraints
1 <= N <= 512and2 <= C <= 1000.- Logits can be any finite float, also values larger than 700.
- Do not change the input arrays.
- Use numpy only.
Examples
pythonlogits = np.array([[1.0, 2.0, 3.0]])
softmax(logits)text[[0.09003057 0.24472847 0.66524096]]pythonlogits = np.array([[2.0, 1.0, 0.1], [0.5, 2.5, 0.3]])
targets = np.array([0, 1])
cross_entropy(logits, targets)text0.31853977The gradient of the same batch has one row for each example. Each row sums to 0.
Hints
4 hintsSolution and notes
LockedPass every check with Submit to open the reference solution and the notes.
Run it on your computer
Clone the repository, install numpy and run the same checks in a terminal:
python3 scripts/practice/run.py softmax-cross-entropy my_answer.py
python3 scripts/practice/run.py softmax-cross-entropy my_answer.py --examplesStart my_answer.py from starter.py.
Your code is saved in this browser as you type. On a phone you can read and edit the code, but the checks are easier to use on a desktop.
Keyboard shortcuts
- Ctrl Enter
- Run the examples
- Ctrl Shift Enter
- Submit
- Tab / Shift Tab
- Indent or outdent the lines
- Esc then Tab
- Move the focus out of the editor
- Alt H
- Show the next hint
On a Mac, use Cmd in place of Ctrl.
Select Run to check the examples, or Submit to run every check.