1. Why Output Three Numbers for Three-Class Classification?
Previously we predicted a single number using . Now, to classify comments as positive, negative, or neutral, we give each category its own set of weights and bias, computing one score for each:
Writing them together:
is the logits, meaning the raw scores before conversion to probabilities.
Is z equal to W * x + b?
Yes. Here is the score, and later is the probability. We need to keep them separate.
If a sample has features and the task has classes, we write single-sample input uniformly as a column vector:
In this notation, each row of is responsible for one class, and each column corresponds to one input feature. The number of rows in equals the number of classes.
Suppose there are three classes (positive, negative, neutral), then has three rows.
So how is the number of input features determined?
It's determined by how we represent samples numerically. For example, if we represent comments using "number of positive words, number of negative words," the input is two numbers; if we add "number of exclamation marks," the input becomes three numbers. These are handcrafted features just for convenience. Later we'll learn word embeddings.
With three classes and three input features, is . The two 3's happen to be the same, but their meanings differ—one is the number of rows, the other the number of columns.
2. Why Can't Raw Scores Be Used Directly as Probabilities?
Suppose the three logits are:
I think they can't be used as probabilities because they don't sum to one hundred percent.
Let me check the arithmetic: happens to equal . The real problem is that it contains negative numbers and numbers greater than .
Class probabilities must satisfy two requirements: each value is in , and the sum equals . Softmax performs exactly this conversion:
First we take the exponential to make every term positive; then divide by the sum to make the final sum equal :
Substituting the scores from earlier:
| Class | Logit | Exponential (approx.) | Probability (approx.) |
|---|---|---|---|
| Positive | 2 | 7.389 | 0.8438 |
| Negative | −1 | 0.3679 | 0.0420 |
| Neutral | 0 | 1 | 0.1142 |
The class with the highest score still has the highest probability. However, softmax reflects the relative relationship between scores. If all logits increase by the same constant :
The probabilities don't change at all. So we cannot look at a single logit in isolation; we must consider how it changes relative to other classes.
3. How Do We Calculate Loss for Classification?
For cases where each sample has exactly one correct class, cross-entropy can be written as:
The higher the probability of the correct class, the lower the loss:
| Probability of Correct Class | Loss (approx.) |
|---|---|
| 0.9 | 0.105 |
| 0.5 | 0.693 |
| 0.1 | 2.303 |
When the probability is , ; this is the ideal boundary value. With finite real-valued logits, ordinary softmax probabilities are strictly less than and can only approach it.
Suppose the correct label is "negative," but the model assigns negative a probability of about :
We take the probability corresponding to the correct label, not the model's highest predicted probability. Even if the model chooses the wrong class, we can still compute the loss.
4. So with Three Classes, Do We Calculate Loss Three Times?
When I saw the complete formula, I got a bit confused:
Following the order positive, negative, neutral, if the correct answer is negative, the one-hot label is:
Expanding:
So it's the sum of three cross-entropies.
Let me clarify: it's three class terms added within one cross-entropy, not three independent cross-entropy losses. The one-hot label zeros out the terms for incorrect classes, keeping only the term for the correct class.
One sample, three classes: output three probabilities, get one loss. Two samples, each with three classes: get one loss for each, then average over the batch.
Using different subscripts to distinguish classes and samples:
is the batch size, is the number of classes. The rest of this article derives for single samples first, with labels as a fixed one-hot vector, and without regularization terms.
5. Why Is the Gradient of Softmax + Cross-entropy Simply p − y?
This part deserves careful explanation. Simply memorizing the result is easy to forget; deriving it by substitution is actually straightforward.
Still assume the second class is the correct answer:
Substituting and using :
Taking the partial derivative with respect to (the score of the correct class):
The second part uses the chain rule: the derivative of is , multiplied by the derivative of the inside with respect to , which is .
For the incorrect class , the derivative of is zero:
Similarly for , we get . Combining all three results:
Therefore:
Although the loss ultimately reduces to , 's denominator contains all logits, so other classes also have gradients.
6. From Gradient of Logits to Gradient of Parameters
This distinction is important: is the gradient with respect to , not yet the gradient with respect to weights.
Because:
Applying the chain rule:
Working through today's exercise: with only one input feature , the correct class is negative, and the negative probability is about :
With learning rate :
So both w and b increase, the negative logit increases, and then the softmax probability increases?
In this single-sample, single-layer classifier update, yes. Here , so increasing both parameters raises the negative logit. The gradients for the other two classes are positive, so their logits decrease, raising the probability of the correct class.
Supplement: After Updating Parameters, How Much Does the Logit Actually Change?
What does this formula mean?
First define the change: , where primes indicate values after the update. This isn't a new update rule, but rather substituting the parameter update back into the logit formula to compute the score change.
With just one input feature, the original score is:
We already know the single-sample gradient descent update:
The probabilities and gradients are all computed before the update. For the same input , substituting into the updated score:
Subtracting the old score and combining the two terms:
The comes from the contribution of weight change, and the comes from the contribution of bias change. The weight update is multiplied by the input once; when substituted into , it's multiplied again, producing the square.
Verifying with the negative class from before: , , , thus:
That is, the negative logit increases by . Using the parameter changes calculated earlier directly also gives the same result:
When there are multiple input features, the contribution of each weight change is summed:
And is the sum of squares of all vector components, so it can be abbreviated as:
Since is always positive and the learning rate is also positive, the direction of change is determined by : the logit of the correct class increases, and the logit of incorrect classes decreases.
The prerequisite here is: the input vector remains unchanged, using only the gradient from this single sample, updating the weights and biases of this layer with the same learning rate, and using ordinary gradient descent without momentum or regularization. Batch updates mix in gradients from other samples; when updating the entire MLP simultaneously, the hidden representation received by this layer may also change. Therefore, we cannot directly generalize to "each step of any batch or entire MLP is guaranteed to reduce loss for every sample."
7. Why discuss ReLU before adding hidden layers?
Suppose we only add another linear computation:
Combining them:
We computed two layers, but it's still the same form of weighted sum plus bias. Strictly speaking, with bias it's called an affine transformation; the course often calls such layers linear layers.
In matrix form we can also combine them:
Therefore we need nonlinearity in between. ReLU is:
Negative numbers become zero, positive numbers stay the same. After adding it:
When I get , when I get . The entire function becomes:
A kink point appears—it's no longer a single global straight line. This is the change brought by nonlinearity in this example.
8. Extending from one hidden unit to four
The complete architecture used today is: three input features, four ReLU hidden units, three classes.
| Quantity | Shape | Meaning |
|---|---|---|
| Input features | ||
| Each row computes weighted sum for one hidden unit | ||
| First layer bias, pre-activation, post-activation | ||
| Each row computes score for one class | ||
| Output bias, scores, probabilities, labels |
If we transpose h, wouldn't W2 be 3×4?
The shape of is correct, but we don't need to transpose here:
If we transpose , we couldn't multiply at all. First stick with the convention of using column vectors, then check that the inner dimensions match.
Without a hidden layer, classifying directly with softmax is usually called Softmax Regression; now with a ReLU hidden layer added, it's an MLP for multiclass classification. The number of hidden units is a structural choice we make, not equal to the number of classes.
9. Backpropagation: multiply along one path, add multiple paths
First, consider a single hidden unit:
If we already know coming back from later, then:
That is:
When , the ReLU derivative is ; when it is . At it is not differentiable; implementations typically choose .
In today's local exercise, given , the result is . This is a local practice example of the chain rule with upstream gradient, not the softmax gradient from the three-class sample earlier.
If the same affects two outputs:
Then:
In the exercise, the two paths contribute and respectively, for a total gradient of . Different paths can partially cancel each other out.
Therefore, the two rules of backpropagation are: multiply along a path, add when multiple paths converge.
10. Today's most valuable insight: why use the transpose in backpropagation?
The forward pass is:
Let . The gradient passed back to the hidden layer is:
Shape check:
But just saying "so the dimensions multiply" is not enough. The real reason comes from looking at a single hidden unit :
connects to three outputs; the weights of these three connections are in column of . We need to multiply this column element-wise with the output gradients and sum them.
Taking the transpose converts this column into a row, so we can use matrix multiplication to simultaneously compute the aggregation for all hidden units at once.
In the forward pass, each row of weights collects inputs to compute one output; in the backward pass, each column of weights collects the gradient contributions from all outputs to the same input.
This is not inversion, nor is it working backward through the forward computation to recover the original input. The matrix is not even necessarily square. We are computing how sensitive the loss is to intermediate quantities.
11. Gradient through ReLU: element-wise multiplication
We also need to pass from to the pre-activation :
denotes element-wise multiplication, not matrix multiplication.
Another local exercise today gives:
Thus:
The second and fourth units have negative pre-activation values, so the gradient for this sample is zeroed out at these locations. This doesn't mean these parameters never change: other samples might activate them; updates with momentum, regularization, etc. cannot be judged by this term alone.
12. Finally, how do we get the weight gradients for the first layer?
Because:
We have:
Given the input:
The weight gradient for the first hidden unit is .
Is the third one −1.6, −0.8, 0.8?
Yes, . Putting all four rows together:
The shape is , same as . This operation of multiplying a column vector by a row vector is called an outer product.
The transpose here serves a different purpose than before:
- : Aggregates gradients across different output paths to obtain the gradient for the hidden output.
- : Multiplies the gradient of each hidden unit by each input respectively to get the weight gradient for each connection.
13. Computing gradients is not the same as updating parameters
You also need to update parameters using the previous formula: 1 − learning rate × gradient.
The operation is understood correctly, but is just the initial weight in the previous example. The general formula is:
There is also a key distinction: and are computed intermediate results, not directly learned parameters. After computing , you must continue to compute the gradients for , and then update the parameters. The next forward pass will recompute the hidden layer outputs.
For the network here, what is learned is .
Backpropagation is responsible for computing gradients; gradient descent is responsible for using gradients to update parameters. A typical training step should first compute all gradients using the same set of forward parameters, then update them uniformly. Do not modify first and then use the new to compute for this step.
14. Complete formulas together; during review you can explain line by line
Here we complete the output layer parameter gradients. It follows the same "gradient times input" rule as the first layer; the input to the output layer is .
Forward: compute predictions and loss
Backward: compute gradients of intermediate quantities and parameters
Update: each parameter minus learning rate times its own gradient
For batch-averaged loss, average the gradients of each sample with respect to the same parameter, then update. All samples must be computed based on the parameters before this update.
15. Where I am in learning now, and how to review
What was initially worked through today is an "MLP with one ReLU hidden layer plus softmax multiclass output." I can manually compute local examples and understand gradient paths and shapes, but have not yet independently completed a full network numerical computation or code training.
During review, you can first cover the answers and ask yourself:
- Why is a single sample loss for three classes one loss rather than three separate losses?
- Can you derive from ?
- What does one column of represent, and why do we use it to aggregate in the backward pass?
- Which intermediate quantity's gradient does ReLU zero out?
- Why is the weight gradient "the incoming gradient times this layer's input"?
- After computing , why can't we directly say the parameters are already updated?
Explaining these clearly and then computing a complete example yourself will validate your understanding better than just knowing the formulas. Later when connecting word embeddings, you can continue asking: where do input vectors come from, and can they also be learned through gradients?
Corresponding slides
Source from course Lecture3_DeepLearning_Background.pdf, page numbers according to PDF reader counting, with cover page as page 1.
| Pages | Corresponding content |
|---|---|
| 17–20 | Multiclass, one-hot, class scores, and softmax |
| 22–24 | Nonlinearity and why activation functions are needed |
| 27–38 | Multilayer networks, layer notation, and forward passing |
| 39–42 | Loss, forward and backpropagation, chain rule |
| 44–60 | Layered computation and gradient propagation |
The ReLU numerical examples, softmax cross-entropy derivation, and notation in this document come from today's supplementary explanations and are not verbatim transcriptions from the slides. The Lecture 5 uploaded today covers Sequence Modeling; we first consolidate the MLP fundamentals needed to understand it, and have not yet begun CNN, RNN, LSTM, and GRU.