Find a course

Module 2: From Neurons to NetworksLesson 5 of 1114 min

Outputs and Loss Functions

Choose the right output layer for regression and classification, and calculate mean squared error and cross-entropy loss with real numbers.

Step 1 of 14Learn

How wrong is "70% cat"?

A network looks at a photo of a cat and says "cat: 0.70, dog: 0.25, fox: 0.05." Is that good? It picked the right answer, but a better network might have said 0.98. To improve, training needs a single number that says how wrong each prediction is. That number is the loss, and the formula that computes it is the loss function (also called a cost or objective function). Training means one thing: adjust the weights to make the average loss over the training data as small as possible.

The right loss depends on the right output layer, and both depend on the task:

  • Regression (predict a number, such as a house price): one output neuron with no activation, so it can produce any value. Loss: mean squared error.
  • Binary classification (yes or no, such as spam): one output neuron with sigmoid, giving a probability. Loss: binary cross-entropy.
  • Multi-class classification (exactly one of K classes, such as digit 0–9): K outputs with softmax. Loss: categorical cross-entropy.
  • Multi-label classification (any number of tags, such as "beach" and "sunset" on one photo): K outputs, each with its own sigmoid.

Mismatching these, for example putting ReLU on a regression output that must sometimes be negative, is a classic bug that no amount of training fixes.

Step 2 of 14Practice · Match the pairs

Match each task to the output layer it needs.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. Predict tomorrow's temperature in degrees
  2. Decide whether a transaction is fraudulent
  3. Identify which of 50 bird species is in a photo
  4. Tag a news article with any of 20 topics

Step 3 of 14Learn

Mean squared error

For regression, the standard loss is mean squared error (MSE): for each example, take the error (prediction minus target), square it, and average over all examples.

MSE = (1/n) · Σ (prediction − target)2

Example: a model predicts house prices (in hundreds of thousands of dollars) of 3, 5 and 2, and the true prices are 2, 5 and 4. The errors are 1, 0 and −2. Squared: 1, 0 and 4. MSE = 5/3 ≈ 1.67.

Why square? Squaring makes every error positive, so overestimates and underestimates can't cancel each other out. It also punishes big errors much more than small ones: an error of 2 costs four times as much as an error of 1. Usually that is what you want, but it means a few extreme outliers (a mansion in a dataset of apartments) can dominate training. Mean absolute error (MAE), the average of |error|, is less sensitive to outliers. The square root of MSE, called RMSE, is often reported because it is in the original units: here √1.67 ≈ 1.29, or about $129,000.

Step 4 of 14Practice · Work it out

A model predicts 4, 7 and 10. The true values are 5, 7 and 7. What is the mean squared error? Give two decimal places.

Step 5 of 14Learn

Cross-entropy: punishing confident mistakes

For classification, the standard loss is cross-entropy. With softmax outputs, it boils down to a strikingly simple rule: look up the probability the network gave to the correct class, p, and compute

loss = −ln(p)

Probability on the correct classLoss
0.990.01
0.900.11
0.500.69
0.102.30
0.014.61

A perfect, confident answer costs almost nothing. A hesitant answer costs a little. A confident wrong answer (1% on the truth) costs a lot, and the loss grows without limit as p approaches zero. That steep penalty gives a strong learning signal exactly where the network is most mistaken.

Here's a useful sanity check: a network that knows nothing and spreads probability evenly over K classes gives p = 1/K, so its loss is ln(K). For 10 digits that's ln(10) ≈ 2.30. If your untrained model starts near 2.30, its setup is plausible; if training never gets below it, the model is learning nothing.

For binary classification with a sigmoid output p and label y (0 or 1), binary cross-entropy is −[y·ln(p) + (1 − y)·ln(1 − p)], which again is just −ln of the probability given to the true answer.

Step 6 of 14Try the calculator

Cross-entropy calculator

Enter the probability the model gave to the correct class, and the number of classes for comparison.

Cross-entropy loss −ln(p)
0.357
Loss of a uniform guess, ln(K)
2.303
Loss compared with a uniform guess
15.5 %

Step 7 of 14Practice · Work it out

A 4-class classifier assigns probability 0.25 to the correct class. What is its cross-entropy loss for this example? Give two decimal places.

Step 8 of 14Practice · Chart

Cross-entropy loss = −ln(p)

p is the probability the network gave to the correct class. The loss is gentle near 1 and explodes as p approaches 0.

Tap the prediction that is punished hardest.

Tap the point that answers the question, then press Check.

Cross-entropy loss = −ln(p)Line chart with 8 categories: 0.01: 4.61; 0.05: 3; 0.1: 2.3; 0.25: 1.39; 0.5: 0.69; 0.75: 0.29; 0.9: 0.11; 0.99: 0.01.012345loss0.010.050.10.250.50.750.90.99p (correct class)
Computed from −ln(p), rounded.
Cross-entropy loss = −ln(p)
p (correct class)Loss
0.014.61
0.053
0.12.3
0.251.39
0.50.69
0.750.29
0.90.11
0.990.01

Step 9 of 14Note

Step 10 of 14Learn

Reading a classifier's output

After softmax, the predicted class is simply the one with the highest probability, the argmax. For a binary classifier with one sigmoid output, you choose a threshold: predict "spam" when p > 0.5 is the default, but you can move it. A cancer screening tool might flag anything above 0.2 to miss fewer cases, accepting more false alarms; a spam filter might require 0.9 to avoid hiding real email.

Be careful about treating these numbers as trustworthy probabilities. Modern deep networks are often overconfident: among all predictions made with 95% confidence, noticeably fewer than 95% may be correct. A model is well calibrated when its confidence matches its accuracy. Calibration can be checked on held-out data and improved with simple fixes such as temperature scaling, which divides the scores by a constant before softmax to soften overconfident outputs.

Also remember that softmax always produces a distribution over the classes it knows. Show a digit classifier a photo of a cat and it will still announce something like "83% it's an 8." The network has no built-in way to say "none of the above" unless it was trained for that.

Step 11 of 14Diagram

From raw scores to a decision

From raw scores to a decisionProcess diagram: Raw scores (logits) → Softmax → Probabilities → Argmax or threshold → Predicted class.Raw scores (logits)SoftmaxProbabilitiesArgmax or thresholdPredicted class

Tap a shape with to see more.

Raw scores (logits)

The last layer outputs one unbounded number per class, e.g. 2.0, 1.0, −1.0.

Softmax

Exponentiate and divide by the sum, so the outputs are positive and add to 1.

Probabilities

e.g. cat 0.71, dog 0.26, fox 0.03.

Argmax or threshold

Pick the largest probability, or compare one probability with a chosen threshold.

Predicted class

Step 12 of 14Practice · What would you do?

What would you do?

A team is building an email filter that labels each message as spam or not spam. Which output layer and loss should they use?

Step 13 of 14Compare

Matching output layers and losses

AspectRegressionBinary classificationMulti-class classification
ExampleHouse priceSpam or notWhich digit, 0–9
Output neurons1 (or one per target)1One per class
Output activationNone (linear)SigmoidSoftmax
LossMean squared errorBinary cross-entropyCategorical cross-entropy
Metric people readAverage errorPrecision, recall, accuracyAccuracy

Step 14 of 14Practice · Choose one

Why do networks train on cross-entropy loss instead of directly on accuracy?