C.W.K.
Stream
Lesson 03 of 08 · published

Loss Functions

~9 min · training

Level 0Keras Apprentice
0 XP0/97 lessons0/20 achievements
0/120 XP to next level120 XP to go0% complete

The loss is your objective, stated precisely

The loss function is the one number training exists to minimize — it turns "how wrong was that prediction" into a single scalar the optimizer can chase. Pick the wrong one and the model will dutifully optimize the wrong thing, often without throwing an error. So the choice isn't cosmetic; it's a statement of what problem you're actually solving.

Match the loss to the task and the label format together:

LossTaskLabels Format
CategoricalCrossentropyMulti-class classificationOne-hot: [0,0,1,0]
SparseCategoricalCrossentropyMulti-class classificationInteger: 2
BinaryCrossentropyBinary / multi-label0 or 1
MeanSquaredErrorRegressionContinuous values
HuberRobust regressionContinuous (outlier-resistant)

The Sparse vs non-Sparse split trips up everyone once: SparseCategoricalCrossentropy wants integer labels like 2, the plain CategoricalCrossentropy wants one-hot vectors like [0,0,1,0]. Feed one the other's format and you get a shape error at best, silently wrong gradients at worst. For regression, reach for Huber over plain MSE when your data has outliers — it behaves like MSE near zero but like MAE in the tails, so a few wild samples don't dominate the gradient.

from_logits=True — the free stability win

Use from_logits=True when your final layer outputs raw scores with no softmax or sigmoid. It's mathematically identical to applying the activation then the loss, but Keras fuses the two into one numerically stable operation — no intermediate probabilities to underflow. The Code section shows both forms; Option B is the one to default to.

Code

softmax loss vs from_logits=True·python
# Option A: softmax output + standard loss
model.compile(loss="sparse_categorical_crossentropy")

# Option B (preferred): no output activation + from_logits
model.compile(
    loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True)
)

External links

Exercise

Train an MNIST model two ways: (a) softmax + sparse_categorical_crossentropy, (b) no softmax + sparse_categorical_crossentropy(from_logits=True). Compare loss values and final accuracy.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.