Output Activations
Matching a network's final activation to the job its output has to do - regression, binary, or multi-class.
A network that trains happily to an answer it can never give
Predict how many millimetres of rain will fall. Put a sigmoid on the output, because sigmoid is the curve you know.
The network is not undertrained. It is not badly initialised. There is no setting of any of its nine parameters that lets it say "40", because sigmoid's entire range is the interval between 0 and 1 and 40 is not in it. The answer was out of reach before training started.
Training will now do exactly what you asked. It will push the output as close to 1.000000 as it can, and then the loss will stop falling, and the curve will flatten, and from a distance a flattening loss curve looks like convergence.
Before this page - 6 pages6
The Single Neuron
z, and the fact that the activation is the last step and touches one numberLayers and the Forward Pass
the rain network, whose hidden layer every head on this page bolts ontoActivation Functions
sigmoid's range and its slope, and saturation, which is what the break above isLoss Functions
squared error and cross-entropy, which this page pairs with activations rather than redefinesGradients and Gradient Descent
what dL/dz means and why its size decides how far a parameter movesBackpropagation
the chain the cancellation on this page sits at the very end of
The two circles on the left are the rain network's hidden layer, frozen at the values it produced on the previous pages. Everything to the right of them is yours: the logit, the curve applied to it, the loss, and the correct answer. Drag the logit toward "confidently wrong" and watch the two loss rows disagree about how much that should matter.
0:13What this animation shows
Two small networks appear side by side: the left one, labeled "binary: 1 output, sigmoid," ends in a single neuron that lights up green with a probability value; the right one, labeled "multi-class: 3 outputs, softmax," ends in three neurons that light up with three different probability values. This previews the page's central point: an output layer's shape and activation should match the job it has to do.
Drag z toward "confidently wrong" (far from y) and watch cross-entropy's gradient stay large while squared error's shrinks toward zero.
Set the activation to sigmoid, the correct answer to 1, and drag the logit all the way down to -6. The network is now as wrong as this widget lets it be. Which loss sends the bigger correction back, cross-entropy or squared error, and by roughly how much?
Commit to a guess, then open this
Cross-entropy sends -0.997527. Squared error sends -0.002460. That is a factor of about 405.
Squared error is not being cautious. It is being quiet at the exact moment the network most needs shouting at, and the reason is mechanical rather than philosophical: squared error's gradient carries a factor of s(1-s), sigmoid's own slope, and at a logit of -6 that slope is 0.002467. The network's confidence is what silences the correction, and the more confidently wrong it is, the quieter the correction gets.
Cross-entropy's gradient is p - y with nothing else in it, because the s(1-s) cancels exactly. Rung 4 does that cancellation in three lines.
A hidden neuron's output only ever feeds more of your own network, so its range can be whatever is computationally convenient. An output neuron's number has to mean something to whoever reads it, and that meaning decides its activation. Two rules follow and both are load-bearing: the activation has to be able to produce every answer the task allows, and the activation and the loss are chosen together rather than separately. Get the first wrong and the right answer is unreachable however long you train. Get the second wrong and training goes quiet at exactly the moment it should be loudest.
The instrument face
You do not read a temperature off a pressure gauge. A thermometer's face runs -40 to 60 and cannot display 200. A fuel gauge runs empty to full and cannot display "eleven litres". A speedometer starts at 0 and cannot display a negative speed, which is correct, because the quantity cannot be negative. The activation is the scale printed on the face, and the first requirement of a face is that the answer is somewhere on it. The break at the top of this page is a rain gauge with a fuel gauge's face fitted.
Where it breaks downa gauge face is cosmetic - the needle already knows the value. An output activation actually changes the number, so it is the mechanism as well as the display.
WordsThe output layer's obligationWhat a logit is, the two rules that decide the last layer, and why multi-label is not multi-class.Rung 01
A hidden neuron's output only ever feeds more of your own network, so its range can be whatever's computationally convenient. An output neuron's number has to mean something to whoever reads it, "70% chance of rain," not an arbitrary number, and that meaning should decide its activation. The raw, pre-activation number a neuron computes is usually called a logitonce it's about to be fed into a probability-producing function like sigmoid or softmax. "Logit" just means the number before the squashing.
Two rules underneath everything on this page.
The activation must be able to produce every answer the task allows. If rainfall can be 40 mm, an output squashed into 0-to-1 can never say so, no matter how it is trained. If a probability can never be negative, an output that ranges over all real numbers is inviting nonsense.
The activation and the loss are chosen together, not separately. Sigmoid with binary cross-entropy behaves well for a reason the derivation in rung 4 makes exact. Sigmoid with squared error behaves badly for the same reason when the target is a hard 0-or-1 class label, because that is the case where the network can end up confidently wrong, pinned deep in sigmoid's flat region where the slope is nearly zero, and squared error has no way to shout at it. When the target is a genuine fraction sitting somewhere in the middle, like 0.35 of a tank, the network is never pushed into the flat tails and the trap does not spring. Hard class labels, use cross-entropy. Interior fractions, squared error is fine.
NumbersOne hidden layer, three different heads bolted onto itThe same two hidden numbers turned into a millimetre, a probability, and three probabilities - every line worked.Rung 02
Everything below runs on the same network the rest of this module uses, so only the last layer changes. Inputs x1 = 0.80 and x2 = 0.60, one hidden layer of two tanh neurons, giving:
Those two numbers, a1 = 0.885352 and a2 = -0.604368, are the hidden layer's summary of the weather. Everything from here is three different ways of turning them into an answer.
Head 1 - regression
The question: how many millimetres of rain will fall.
The answer can be 0.4 mm or 40 mm. It has no ceiling, so it must not be squashed. The output neuron computes its weighted sum and that number isthe prediction. This is usually called a linear output, or "no activation", and both mean the same thing: the identity function, f(z) = z.
Two symbols in that last block are new, and both are read out loud more easily than they look.
dL/dzo is said "d L by d z-o", and it means "how much does the loss L change when zo changes". The L on top is the thing being affected, the zounderneath is the thing being wiggled. It is the slope idea from the activation pages pointed at a different pair of quantities: instead of "how much does this curve's output move when its input moves", it is "how much does our total wrongness move when this one number moves". A big dL/dzo means zo has a lot of influence over the loss. A dL/dzo of zero means moving zo would not change the loss at all. That quantity, for a parameter rather than for zo, is exactly the gradient page 1 described. It is also the quantity the backpropagation page calls δ; the two names are for one thing, and this page happens to be looking at it at the very end of the chain rather than in the middle.
f'(zo) is said "f prime of z-o", and it is the same thing the activation pages measured: the slope of the output activation f, at the particular point zo. Here the output activation is the identity, whose slope is 1 everywhere, which is why the line reads * 1.
Put together, the line says: how wrong you were, scaled by how much the final curve was willing to pass along. Both symbols recur on this page and the next, and they never mean anything else.
The slope of a linear activation is exactly 1 everywhere, so it never shrinks the training signal and never blocks it. The gradient arriving at the output layer is just "how far off you were, and in which direction". Negative means the prediction was too low.
Do not use cross-entropy here. Cross-entropy takes the logarithm of the prediction, and this prediction is not a probability; it can be 40, and it can be negative, and log of a negative number does not exist. Squared error is the right pairing for an unbounded output.
Two variants, when the answer is constrained:
Softplus is generally the better choice than ReLU on an output that must be positive, for the reason the activation-functions page established: ReLU's exactly-zero region gives an exactly-zero gradient, and an output neuron stuck there stops learning entirely.
Head 2 - binary
The question: will it rain, yes or no.
The answer must be a probability, so it has to sit strictly between 0 and 1. Sigmoid is the standard choice, and the same weighted sum from above is what gets squashed. That raw sum, 1.845916, is the logit.
Notice that the two rows share a weighted sum and differ only in what is done to it. The network's internals did not change at all between the regression head and this one; only the final step and the loss did.
Notice also the sign of the gradient in each case. When it rained and the network said 86%, the gradient is -0.136353: push the logit up, be more confident next time. When it did not rain, the gradient is +0.863647: push the logit down, hard. The size of the gradient is exactly how wrong the probability was, which is the cancellation rung 4 explains.
Head 3 - multi-class
The question: dry, drizzle, or downpour. Exactly one is true.
Now the output layer needs three neurons, one per class, each with its own weights into the same two hidden activations. Three logits come out, and softmax turns them into three probabilities that add to 1.
The block below calls these output weights u. That is only a label: w has been the input-to-hidden weights all module, vwas the single output neuron's weights a moment ago, and ukeeps this head's three sets apart from both. They are ordinary weights and there are six of them plus three biases.
Three separate weighted sums, three separate sets of weights, one shared hidden layer. That is what "one output unit per class" means in practice.
Softmax is the one activation in this entire module that is not applied one number at a time. p_dry depends on z_downpour, because z_downpour is in the denominator. Push one logit up and every other probability goes down, automatically, because they are forced to sum to 1. That coupling is the point, and it is what the next page is about.
The same three logits, run both ways
The three numbers below are not from the rain network, because the rain network does not tag photographs. Take them as any three logits a photo-tagging network might produce; where they came from does not matter here, because the point is entirely about what the two treatments do to the same three numbers.
Look at what softmax did to the first label. Read independently, the network is 76.9% sure the photo is outdoor. Run through softmax, that becomes 29.3%, not because the evidence changed but because it had to give room to "people". Softmax made the labels compete when they were never in competition.
The loss follows the same split. For multi-label, run binary cross-entropy on each label separately and add up the results. With true labels y = (1, 0, 1), meaning outdoor and people are correct and night-time is not:
Three independent yes/no problems that happen to share a network, which is exactly what multi-label is.
PictureOne body, three headsThe same two hidden numbers, three different last layers, with the identical logit drawn twice on purpose.Rung 03
On the stage figure above: the two circles on the far left are a1 = 0.885352 and a2 = -0.604368, the hidden layer, frozen. The dashed circle in the middle is that whole layer treated as one object, because from here on nothing about it matters except the two numbers it produced. The circle on the right is the logit, and it is the only thing you control. The activation is not drawn as a circle at all; it is the arrow leaving that circle, which is the right way to picture it, because the activation is a step and not a place.
The top two branches carry the identical logit, 1.845916, drawn identically because it is identical: the regression head and the binary head compute the same weighted sum and differ only in what they do to it afterwards. The bottom branch is the one that needed a different output layer, because a question with three answers needs three logits, and those three are the only numbers on the figure that are forced to add up to anything.
EquationWhy sigmoid and cross-entropy are chosen as a pairOne calculus rule checked by nudging, then the three-line cancellation the whole pairing rests on.Rung 04
Both symbols in the derivation below were read out loud in rung 2 and neither means anything else anywhere on this site: dL/dz is how much the loss moves when z moves, and s(1-s)is sigmoid's own slope at the point it is sitting at.
The derivation leans on one calculus rule, d/ds[log(s)] = 1/s, so let's verify it first with the same nudge-and-measure method used on the earlier pages: at s=0.5, log(0.5)=−0.6931; at s=0.501, log(0.501)≈−0.6911; the change is 0.0020 over a nudge of 0.001, so slope≈2.0, matching 1/0.5=2.0. ✓
Now the full derivation, in three explicit steps, for a sigmoid output s=σ(z) with binary cross-entropy L=−[y·log(s)+(1−y)·log(1−s)]:
That cancellation is the whole point. Compare a confidently wrong prediction (y=1, s=0.02) under each loss: cross-entropy gives ∂L/∂z = 0.02−1 = −0.98, a strong signal to correct course. Squared error, with no cancellation to save it, gives ∂L/∂z = (0.02−1) * 0.02 * 0.98 = −0.0192, nearly 50 times smaller, exactly when the network is most wrong and most needs a push.
General caseThe whole decision, and the one thing frameworks assumeSix rows that decide every output layer you will build, and why passing a probability to a loss is silent damage.Rung 05
The choice is almost entirely determined by the question you are asking. Here is the whole decision; every row above was one of its lines.
| Task | Output units | Activation | Loss |
|---|---|---|---|
| regression | 1 (or k) | none (linear) | squared error |
| regression, must be > 0 | 1 | softplus or ReLU | squared error |
| regression, bounded 0..1 | 1 | sigmoid | squared error (*) |
| binary classification | 1 | sigmoid | binary cross-entropy |
| multi-class, pick one | k (one per class) | softmax | categorical cross-entropy |
| multi-label, any can be on | k (one per label) | sigmoid, each | binary cross-entropy, summed |
(*) sigmoid with squared error is fine here and a bad idea one row further down. The second rule in rung 1 says why.
A note on the loss names. Squared errormeans "square the miss". You will meet it under several names: mean squared error or MSE when it is averaged over a batch of examples, and it is often written with a 0.5 in front, as the worked blocks on this page do, because that 0.5 cancels a 2 later and makes the gradient come out clean. They are the same idea and the choice between them changes nothing you will care about. This site uses the half-squared form and says so wherever it appears.
One implementation gotcha
Every framework you are likely to use wants logits, not probabilities, handed to its loss function. PyTorch's CrossEntropyLoss applies softmax internally. BCEWithLogitsLoss applies sigmoid internally. Applying the activation yourself and then passing the result in applies it twice, which does not crash, does not warn, and produces a model that trains slowly and badly.
The reason the frameworks do this is not tidiness. Combining the activation and the loss into one operation lets them use the cancellation derived in rung 4 directly, and lets them avoid computing log of a number that may have rounded to exactly 0. It is both faster and more numerically stable than doing the two steps separately. The next page shows the specific arithmetic that goes wrong.
Why this and not that
Why not cross-entropy on a regression output?
Cross-entropy takes the logarithm of the prediction. A rainfall prediction can be 40 and it can be negative, and log of a negative number does not exist. There is nothing to fix here; the pairing is simply undefined.
Why not squared error with a sigmoid?
On a hard 0-or-1 class label, because squared error's gradient carries sigmoid's own slope as a factor and that slope collapses to nearly zero exactly when the network is confidently wrong. On a target that is a genuine interior fraction, like 0.35 of a tank, it is fine, because the network is never pushed into the flat tails in the first place. The decision table lists both cases deliberately.
Why softplus rather than ReLU when the output must be positive?
ReLU's exactly-zero region gives an exactly-zero gradient. An output neuron that lands there stops learning entirely and there is no layer below it to route around the problem. Softplus is never exactly zero, so it is never exactly stuck: at zo = -0.70 it still reports 0.403186 where ReLU reports 0.000000.
Why do frameworks want raw logits?
So they can fuse the activation and the loss into one operation, use the cancellation directly, and avoid taking log of a number that has rounded to 0. Faster and more numerically stable. The cost is that passing a probability in by mistake is silent.
Why is multi-label not just multi-class with more than one right answer?
Because softmax's constraint is a claim about the world: these options are mutually exclusive and one of them is true. On a photo that is outdoor and contains people, that claim is false, and enforcing it makes the model split confidence it should not be splitting.
Can the hidden layers and the output disagree about activation?
They routinely do, and should. ReLU throughout the hidden layers with a sigmoid on the output is the most common binary classifier there is. The previous page's last section says the same thing from the other side.
- logit
- short for "logistic unit", and it is the log-odds log(p / (1 - p)), which is exactly the inverse of sigmoid. So calling the pre-sigmoid number a logit is literally accurate rather than slang: it is the quantity sigmoid was built to undo.
- cross-entropy
- from information theory. Entropy measures the average surprise of a distribution; cross-entropy measures the average surprise you experience if you believe distribution q while the truth is p. Minimising it means making your beliefs less surprising to reality.
- binary vs categorical
- the same formula, one for a two-outcome question with a single output, one for a k-outcome question with k outputs.
- regression
- from Galton's "regression toward the mean", a nineteenth-century observation that tall parents have children closer to average height. The word attached itself to the whole method and now means "predict a number". It has nothing to do with going backwards, and this is worth knowing because the name actively misleads.
- head
- the swappable last layer or few layers. The rest is the "body" or "backbone". The metaphor is exactly the one in rung 3's picture: one body, three heads.
- MSE
- mean squared error, the batch-averaged form of squared error.
- linear output
- the same thing as "no activation": the identity function f(z) = z. Both phrases are in common use.
- What is happening
- The answer is not inside the activation's range, so no parameters exist that reach it. This is the break at the top of the page, reproduced on the instrument.
- Fix
- Choose the activation from the range the answer can take: linear for an unbounded quantity, softplus if it must be positive.
- Watch for
- Sigmoid, squared error, target 2.5, logit at its maximum of 6.0. The output reads
0.997527and the loss reads1.128712. Drag the logit anywhere you like: the loss never goes below1.1287, because the output cannot go above 1.
- What is happening
- Squared error's gradient carries a factor of
s(1-s), which is nearly zero in exactly the region where the network is most wrong. - Fix
- Use binary cross-entropy on a hard 0-or-1 label. Its gradient is
p - y, with sigmoid's slope cancelled out. - Watch for
- Target 1, logit -6.0. The cross-entropy row reads
dL/dz = -0.997527; the squared-error row reads-0.002460. Four hundred times quieter, at the worst possible moment.
- What is happening
- Cross-entropy takes the log of the prediction, and a linear output is not a probability. It can be negative, and
logof a negative number does not exist. - Fix
- Pair a linear output with squared error. If you want cross-entropy, you wanted a probability output, which means sigmoid or softmax.
- Watch for
- With the activation on Linear, try to select cross-entropy and watch the control refuse: the row reads
n/a - needs a probability output. That is this widget being more careful than your framework will be:BCEWithLogitsLossaccepts any real number without complaint, because it is expecting a logit and will apply its own sigmoid.
- What is happening
- The framework applies the activation again. Sigmoid is now applied twice, so the probability you computed is being treated as a logit.
- Fix
- Hand the loss the raw logit and let it apply the activation. In PyTorch that means
BCEWithLogitsLossrather than a sigmoid followed byBCELoss. - Watch for
- The probability
0.863647fed back in as though it were the logit: the output reads0.703422. A double sigmoid maps the entire real line into the band from0.500618to0.730572, a range 0.23 wide. Every possible answer has been compressed into a quarter of the interval, and the loss will still fall a little, and it will look like training.
- What is happening
dL/dz = p - ywithpbetween 0 and 1 andyeither 0 or 1 can never leave the interval from -1 to 1. It is bounded by construction.- Fix
- Nothing to fix. Check the bound before you go looking for a bug: a cross-entropy output gradient at the last layer cannot exceed 1 in magnitude.
- Watch for
- Target 0, logit 6.0, confidently wrong the other way. Cross-entropy's gradient reads
0.997527, which is as large as it can ever get and is exactly what "the network was almost completely wrong" should look like.
- 01Find the logit that makes a sigmoid output exactly 0.500.
Hint
The previous pages already told you where sigmoid crosses its midpoint.Answer
z = 0.0. Sigmoid passes through exactly 0.5 at exactly 0, which is why "the probability is above half" and "the logit is above zero" are the same statement. - 02With the correct answer set to 1 and cross-entropy selected, find the smallest logit that gets the loss under 0.10.
Hint
The loss is -log(p), so you need p above about 0.905.Answer
z = 2.3, givingp = 0.908877and a loss of0.095545. Atz = 2.2the loss is still just above 0.10. Note how expensive certainty is: getting from 50% to 90% cost 2.3 of logit, and getting from 90% to 99% costs another 2.3. - 03With the correct answer at 1, compare both losses' gradients at z = -4 and at z = 0, and say which loss behaves the way you would want.
Hint
One of them gets louder as the network gets more wrong and one gets quieter.Answer
At
z = -4, cross-entropy gives-0.982014and squared error gives-0.017345. Atz = 0, cross-entropy gives-0.500000and squared error gives-0.125000. Cross-entropy roughly doubles as the network goes from unsure to badly wrong. Squared error shrinks by a factor of seven over the same move. Squared error is quietest exactly where you need it loudest. - 04Switch to a linear output with a free target and make the loss exactly zero.
Hint
With the identity activation, the prediction is the logit.Answer
Set the target and the logit to the same value, for example both at 1.8. The prediction equals the logit exactly, so the miss is 0.000000 and the loss is 0.000000. This is why a linear output never blocks a correction: its slope is 1 everywhere, so
dL/dzois just "how far off you were, and in which direction", with nothing scaling it. - 05Hardest. Demonstrate for yourself that applying sigmoid twice destroys the network's range. Read the sigmoid output at z = -6 and at z = +6, then apply sigmoid to each of those two results by hand.
Hint
You are treating a probability as though it were a logit, which is exactly the mistake in the mapper above.Answer
sigmoid(-6) = 0.002473andsigmoid(6) = 0.997527. Applying sigmoid again gives0.500618and0.730572. The entire real line, every logit the network could possibly produce, has been compressed into a band 0.23 wide that never gets below 0.5. A model in this state cannot express low confidence about anything, and its loss curve will still go down.
- Fraud, spam, click-throughEvery fraud score on a card transaction, every spam probability, and every ad click-through estimate you have been on the receiving end of is a linear layer followed by one sigmoid, trained with binary cross-entropy. It is the most-deployed output layer in the world.
- Why they report a probabilityThose systems report a probability rather than a yes or a no because of the fourth row of the decision table: the business wants to set its own threshold, and a threshold needs a number to compare against.
The last layer is a translator, not a thinker.
Ask it for a quantity and it must be able to say forty. Ask it for a probability and it must be able to say 3%. Ask it to pick one of three and it must make the three add up. Choose the translator by looking at the question, never by looking at the network.
The multi-class head in rung 2 worked, and it was handed to you. Three logits went in, three probabilities came out, and the reason there is an exponential in the middle was never given.
It is not obvious, and the obvious alternative, divide each score by the total, fails in two specific ways that are worth watching fail. The last page of this module takes softmax apart, including one line that appears in every real implementation and in no textbook formula.