What is a Loss Function?
The loss function is the model's scorecard for mistakes. It compares the model's prediction with the true answer and gives one number. A big number means a bad prediction. A small number means a good prediction. Training is the process of making this number as small as possible.
Simple example: You throw darts. The loss is the distance between the dart and the center. Learning means that your throws land closer and closer to the center.
Choosing a Loss Function
| Problem | Output layer | Loss |
| Regression (predict a number) | Dense(1) | mse or mae |
| Binary classification | Dense(1, activation="sigmoid") | binary_crossentropy |
| Multi-class, labels are integers (0, 1, 2) | Dense(n, activation="softmax") | sparse_categorical_crossentropy |
| Multi-class, labels are one-hot vectors | Dense(n, activation="softmax") | categorical_crossentropy |
Mean Squared Error (MSE)
MSE takes the difference between prediction and truth, squares it and averages over all samples. Squaring makes big mistakes count much more.
python
import numpy as np
y_true = np.array([100, 150, 200])
y_pred = np.array([110, 140, 230])
mse = np.mean((y_true - y_pred) ** 2)
mae = np.mean(np.abs(y_true - y_pred))
print(mse, mae) # 366.67 16.67
Binary Crossentropy
Used when the answer is yes or no. It punishes the model heavily when it is confident but wrong.
python
import keras
y_true = [1.0, 0.0, 1.0]
y_pred = [0.9, 0.1, 0.2] # the last prediction is badly wrong
loss = keras.losses.BinaryCrossentropy()
print(float(loss(y_true, y_pred)))
Categorical vs Sparse Categorical Crossentropy
Both are used for multi-class problems. The only difference is the label format.
python
# Labels as integers -> sparse_categorical_crossentropy
y = [2, 0, 1]
# Labels as one-hot vectors -> categorical_crossentropy
y_onehot = [[0, 0, 1],
[1, 0, 0],
[0, 1, 0]]
# Convert integers to one-hot
y_onehot = keras.utils.to_categorical(y, num_classes=3)
Using Loss in Keras
python
model.compile(optimizer="adam", loss="mse")
model.compile(optimizer="adam", loss="binary_crossentropy")
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy")
# Or with a loss object (gives you more options)
model.compile(
optimizer="adam",
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=False)
)
What is from_logits? If your last layer has no softmax or sigmoid, it outputs raw scores called logits. In that case set from_logits=True. Otherwise keep it False.
Conclusion
The correct loss function depends on your task. Match it with the label format and the output layer, and your model will train properly.
Quick Summary: MSE for regression, binary crossentropy for yes or no, and (sparse) categorical crossentropy for many classes.