Python & Data Science
Deep Learning Under review

Loss Functions Reference Mse Mae Cross Entropy And

You’re at a carnival, and the prize is a giant stuffed panda. The game is simple: throw a dart at a board. The closer you get to the bullseye, the bigger the prize. But the carny running the booth has a strange rule—he’ll measure your “wrongness” in two different ways, and you have to pick which one he uses before you throw.

Option A: he measures the straight-line distance from your dart to the bullseye, squares it, and that’s your penalty. Option B: he just measures the straight-line distance, no squaring. Which do you choose?

If you’re a little off, both options give a small penalty. But if you completely miss the board? Option A squares that huge mistake, turning a 10-inch miss into a 100-point penalty. Option B just calls it 10. The way we measure “wrongness” completely changes the game—and it changes what you’d practice to get better.

This is exactly the problem every machine learning model faces. When a model makes a prediction, we need a single number that says, “You were this wrong.” That number is the loss, and the function that calculates it is the loss function. It’s the ruler we use to measure mistakes. And just like in our dart game, different rulers care about different things. Some scream bloody murder at huge mistakes, while others are more forgiving.

In this article, we’re going to become fluent in the three most important loss functions in machine learning: Mean Squared Error (MSE) , Mean Absolute Error (MAE) , and Cross-Entropy. We’ll build each one from a relatable scenario, walk through the math with real numbers and plain English, and write code that calculates them from scratch. By the end, you’ll have a clear, intuitive framework for deciding which ruler to use—and a reference table you can come back to whenever you need it.

Why Loss Functions Matter: The Steering Wheel of Learning

Before we meet our three rulers, let’s zoom out. Why does any of this matter? Isn’t a loss function just a way to grade a model’s performance?

It’s much more than that. Think of a loss function as the steering wheel of a machine learning model. Here’s what happens during training:

  1. The model makes a batch of predictions.
  2. The loss function looks at those predictions and the true answers, and spits out a single number: “You’re this bad right now.”
  3. The model’s learning algorithm (like gradient descent) uses that number to tweak all the model’s internal knobs and dials, trying to make the number smaller next time.

The key insight—and this is the hardest part to internalize—is that the loss function doesn’t just measure performance. It defines what “good” means. If you change the ruler, you change what the model optimizes for.

Imagine you’re training a model to predict house prices, and you choose a loss function that absolutely despises large errors. Your model will work overtime to get the expensive mansions right, even if that means being a little sloppier on the average homes. Choose a different loss function, and the model might spread its attention more evenly. Same data, same model architecture, but a different loss function steers you to a completely different destination.

This is why choosing the right loss function is one of the most consequential decisions you’ll make. For predicting numbers (regression), the central choice is MSE vs. MAE, driven by how you feel about outliers. For predicting categories (classification), cross-entropy is the natural choice—and we’ll see exactly why. Let’s start with the outlier punisher.

MSE: The Outlier Punisher

Let’s make this concrete. You’re building a model to predict home sale prices. You have three houses:

  • House A sold for 200,000.Yourmodelpredicted200,000. Your model predicted 210,000.
  • House B sold for 300,000.Yourmodelpredicted300,000. Your model predicted 290,000.
  • House C sold for 500,000.Yourmodelpredicted500,000. Your model predicted 450,000.

Your model is off by 10,000onthefirsttwohouses,andoffby10,000 on the first two houses, and off by 50,000 on the third. How wrong is your model, overall?

If you just average the errors, the 10kand−10k and -10k cancel out, and you get a misleadingly small number. So we need a way to make all errors positive before averaging. Mean Squared Error (MSE) does this by squaring each error.

Here’s the formula in plain English:

Take each error (actual minus predicted), square it to make it positive and to heavily punish big misses, then average all the squared errors.

In mathematical notation:

MSE = (1/n) * Σ (y_true - y_pred)²

Let’s walk through our three houses step-by-step:

  1. House A: Actual 200k,Predicted200k, Predicted 210k → Error = -10k.Squarederror=(−10)2=100(inunitsof10k. Squared error = (-10)² = 100 (in units of 1k²).
  2. House B: Actual 300k,Predicted300k, Predicted 290k → Error = +$10k. Squared error = 10² = 100.
  3. House C: Actual 500k,Predicted500k, Predicted 450k → Error = +$50k. Squared error = 50² = 2,500.

Now average them: (100 + 100 + 2500) / 3 = 2700 / 3 = 900.

Our MSE is 900 (in units of thousands-of-dollars squared). What does that actually mean? It means that, on average, the square of our error is 900,000,000 (since we were working in thousands). But more importantly, look at where that number came from. The 50kmissonHouseCcontributed2,500tothenumerator.Thetwo50k miss on House C contributed 2,500 to the numerator. The two 10k misses contributed only 100 each. That one large error made up over 92% of the total penalty.

This is the defining trait of MSE: it makes your worst mistakes disproportionately influential. A 50kerrorisn’t5timesworsethana50k error isn’t 5 times worse than a 10k error—it’s 25 times worse. The model will move mountains to reduce those big errors, even if it means accepting slightly worse performance on the “easy” cases.

Here’s that whole computation expanded, one step at a time:

(200−210)2+(300−290)2+(500−450)2\term{a}{(200 - 210)^2} + \term{b}{(300 - 290)^2} + \term{c}{(500 - 450)^2}

Square each error so the sign can’t cancel.

100+100+2500\term{a}{100} + \term{b}{100} + \term{c}{2500}

The 50kmissis25xworsethanthe50k miss is 25x worse than the 10k misses, not 5x — squaring made it 25002500.

27002700

Total squared error: 100+100+2500=2700100 + 100 + 2500 = 2700.

27003=900\frac{2700}{3} = 900

Average over the three houses: MSE =900= 900 (thousands of dollars squared).

Let’s see this in code.

import numpy as np
from sklearn.metrics import mean_squared_error

# Our three houses: actual and predicted prices (in thousands of dollars)
y_true = np.array([200, 300, 500])
y_pred = np.array([210, 290, 450])

# Calculate MSE manually
squared_errors = (y_true - y_pred) ** 2
mse_manual = np.mean(squared_errors)

print("Squared errors for each house:", squared_errors)
print("Manual MSE:", mse_manual)

# Verify with sklearn
mse_sklearn = mean_squared_error(y_true, y_pred)
print("Sklearn MSE:", mse_sklearn)

# Show the contribution of each house to the total loss
contributions = squared_errors / np.sum(squared_errors) * 100
print("Contribution of each house to total MSE:")
for i, (actual, pred, contrib) in enumerate(zip(y_true, y_pred, contributions)):
    print(f"House {i+1}: Actual=${actual}k, Predicted=${pred}k -> Contribution: {contrib:.1f}%")

When you run this, you’ll see that House C—the one with the $50k miss—contributes over 92% of the total MSE. The model’s entire focus during training will be on fixing that one big mistake. This is why MSE is the right choice when large errors are genuinely unacceptable: think medical dosing, where a big miss could be catastrophic, or safety-critical engineering predictions.

There’s also a deeper statistical reason MSE is so common. If you assume that your prediction errors follow a bell-curve (normal) distribution, then minimizing MSE is mathematically equivalent to finding the most likely model given the data. You don’t need to remember this now, but when you see “MSE assumes Gaussian errors” in a paper, this is what they’re referring to.

MAE: The Outlier Ignorer

Now let’s measure the same three houses with a different ruler. What if, instead of squaring the errors, we just take their absolute value?

Mean Absolute Error (MAE) does exactly that. The formula in plain English:

Take each error, drop the negative sign (absolute value), then average them.

In mathematical notation:

MAE = (1/n) * Σ |y_true - y_pred|

Let’s recalculate for our three houses:

  1. House A: Error = -$10k → Absolute error = 10.
  2. House B: Error = +$10k → Absolute error = 10.
  3. House C: Error = +$50k → Absolute error = 50.

Average: (10 + 10 + 50) / 3 = 70 / 3 = 23.3.

Our MAE is 23.3 (in thousands of dollars). In plain English: on average, our predictions are off by about $$23,300. That’s a number you can say to a business stakeholder and they’ll understand immediately.

Now compare the two:

  • MSE: 900 (a number dominated by the $50k miss)
  • MAE: 23.3 (a number that treats the 50kmissasexactly5timesworsethana50k miss as exactly 5 times worse than a 10k miss)

The 50kerrorcontributed50totheMAEnumerator,whileeach50k error contributed 50 to the MAE numerator, while each 10k error contributed 10. That’s proportional—5 times the error, 5 times the penalty. No squaring, no amplification.

This makes MAE robust to outliers. If your data has a few crazy values—a mansion that sold for $$5 million in a dataset of $200k homes, or a sensor that glitched and recorded 999°F—MAE won’t let those points hijack the training process. The model will acknowledge them, but it won’t obsess over them.

Let’s verify with code.

import numpy as np
from sklearn.metrics import mean_absolute_error, mean_squared_error

# Same three houses
y_true = np.array([200, 300, 500])
y_pred = np.array([210, 290, 450])

# Calculate MAE manually
absolute_errors = np.abs(y_true - y_pred)
mae_manual = np.mean(absolute_errors)

print("Absolute errors for each house:", absolute_errors)
print("Manual MAE:", mae_manual)

# Verify with sklearn
mae_sklearn = mean_absolute_error(y_true, y_pred)
print("Sklearn MAE:", mae_sklearn)

# Side-by-side comparison with MSE
mse = mean_squared_error(y_true, y_pred)
print(f"\nMSE: {mse:.1f}")
print(f"MAE: {mae_sklearn:.1f}")
print(f"Ratio (MSE / MAE): {mse / mae_sklearn:.1f}")
print("\nInterpretation: MSE is {:.0f} times larger than MAE because it amplifies the $50k error.".format(mse / mae_sklearn))

The ratio between MSE and MAE tells a story. In a dataset with no outliers, they’ll be relatively close. A large ratio is a red flag: it means you have some big errors that MSE is screaming about while MAE is staying calm.

The trade-off with MAE is that it gives a weaker learning signal for large errors. During training, the gradient (the nudge the model gets) is constant regardless of error size. A miss of 50 gets the same strength of nudge as a miss of 5—just in the right direction. MSE, by contrast, gives a much stronger nudge for the 50-miss. This can make MAE slower to converge, but it also makes it less likely to overfit to outliers.

Statistically, MAE is the natural loss if you assume your errors follow a Laplace distribution (a sharper peak, fatter tails than the bell curve). Again, just file that away—you’ll hear “MAE assumes Laplacian errors” and now you know what it means.

MSE vs. MAE: The Decision That Changes Your Model

So we have two rulers. One screams at outliers, one shrugs at them. How do you choose? Let’s make the difference visual.

import numpy as np
import matplotlib.pyplot as plt

# Create a range of error values from -10 to +10
errors = np.linspace(-10, 10, 400)

# Calculate MSE and MAE for each error value
mse_values = errors ** 2
mae_values = np.abs(errors)

fig, ax = plt.subplots(figsize=(10, 6))

ax.plot(errors, mse_values, label='MSE (squared error)', linewidth=2.5, color='#e74c3c')
ax.plot(errors, mae_values, label='MAE (absolute error)', linewidth=2.5, color='#3498db')

# Highlight the agreement zone near zero
ax.axvspan(-1, 1, alpha=0.15, color='green')
ax.annotate('They agree here\n(small errors)', xy=(0, 1), xytext=(3, 15),
            arrowprops=dict(arrowstyle='->', color='green'), fontsize=11, color='green', fontweight='bold')

# Highlight the divergence at large errors
ax.annotate('MSE punishes\nmuch harder here', xy=(8, 64), xytext=(5, 80),
            arrowprops=dict(arrowstyle='->', color='#e74c3c'), fontsize=11, color='#e74c3c', fontweight='bold')

ax.annotate('MAE stays\nproportional', xy=(8, 8), xytext=(5, 25),
            arrowprops=dict(arrowstyle='->', color='#3498db'), fontsize=11, color='#3498db', fontweight='bold')

ax.set_xlabel('Error (y_true - y_pred)', fontsize=13)
ax.set_ylabel('Loss Value', fontsize=13)
ax.set_title('MSE vs MAE: How They Punish Errors of Different Sizes', fontsize=15, fontweight='bold')
ax.legend(fontsize=12)
ax.grid(True, alpha=0.3)
ax.set_xlim(-10, 10)
ax.set_ylim(0, 105)

plt.tight_layout()
plt.show()

Look at the shape. MAE is a V-shape—straight lines, proportional punishment. MSE is a parabola—curved, accelerating punishment. For a small error of 1 unit, both give a loss of 1. They agree. For a large error of 5 units, MSE gives 25 while MAE gives 5. MSE is screaming five times louder.

Now here’s the interesting part: this difference doesn’t just change the score your model gets. It changes what your model learns. A model trained with MSE will contort itself to reduce the largest errors, because that’s where the biggest loss reduction lives. A model trained with MAE will spread its attention more evenly across all errors.

The decision rule in plain English:

  • Use MSE when large errors are genuinely unacceptable. If you’re predicting drug dosages, a 10x overdose could kill someone. You want the model to obsess over preventing large mistakes, even if it means being slightly less accurate on routine cases.
  • Use MAE when your data has outliers you don’t want to overfit to. Real-estate prices with a few mansions, sensor data with occasional glitches, user behavior data with bots—in all these cases, you want a model that captures the typical pattern, not one that chases the weirdos.

There’s a middle ground called Huber loss that acts like MSE for small errors and MAE for large ones, but that’s a story for another article. The point is understanding the trade-off.

Cross-Entropy: The Probability Police

Now let’s switch domains. Everything we’ve discussed so far is for regression—predicting a number on a continuous scale. But what about classification—predicting which category something belongs to?

Imagine a spam filter. You give it an email, and it outputs a number: 0.99. That means it’s 99% confident the email is spam. But the email is actually a normal message from your boss. How wrong is the model?

This is a different kind of wrongness. It’s not about distance on a number line. It’s about confidence in the wrong answer. A model that says “I’m 99% sure this is spam” when it’s actually ham has made a catastrophic error—it was extremely confident and extremely wrong. A model that says “I’m 51% sure this is spam” is also wrong, but it was at least uncertain.

Cross-entropy loss measures exactly this. It asks: given the model’s predicted probability for the true class, how surprised would you be to see the true label? The lower the probability the model assigned to the truth, the bigger the penalty.

Let’s build the intuition with numbers. For binary classification (two classes: spam or ham, cat or dog, yes or no), the formula is:

L = -(y * log(p) + (1-y) * log(1-p))

In plain English:

  • y is the true label (1 for spam, 0 for ham).
  • p is the model’s predicted probability that the email is spam.
  • If the email really is spam (y=1), the second term (1-y) * log(1-p) becomes zero, and we’re left with -log(p). The higher p is, the smaller -log(p) becomes. If the model was confident and correct (p=0.99), the penalty is tiny. If it was confident and wrong (p=0.01), the penalty is huge.
  • If the email is ham (y=0), the first term disappears, and we get -log(1-p). Now the model is penalized for giving a high probability to spam—because 1-p is the probability it assigned to ham.

Let’s calculate this for three scenarios where the true label is 1 (spam):

  1. Model predicts p=0.9 (confident and correct): L = -log(0.9) ≈ 0.105
  2. Model predicts p=0.5 (uncertain guess): L = -log(0.5) ≈ 0.693
  3. Model predicts p=0.1 (confident and wrong): L = -log(0.1) ≈ 2.303

Look at those numbers. A 90%-confident correct prediction costs almost nothing (0.105). A 50-50 guess costs 0.693. But a 90%-confident wrong prediction costs 2.303—over 20 times more than the confident correct one. This is the probability police in action: being confidently wrong is the worst crime.

Let’s verify this in code.

import numpy as np
from sklearn.metrics import log_loss

# Three scenarios: true label is 1 (spam) in all cases
y_true_binary = np.array([1, 1, 1])

# Model's predicted probability of class 1 (spam)
y_pred_proba = np.array([0.9, 0.5, 0.1])

# Calculate binary cross-entropy manually
def binary_cross_entropy_manual(y_true, y_pred):
    # Clip predictions to avoid log(0)
    y_pred = np.clip(y_pred, 1e-15, 1 - 1e-15)
    loss = -(y_true * np.log(y_pred) + (1 - y_true) * np.log(1 - y_pred))
    return loss

manual_losses = binary_cross_entropy_manual(y_true_binary, y_pred_proba)
print("Manual binary cross-entropy for each scenario:")
for i, (p, loss) in enumerate(zip(y_pred_proba, manual_losses)):
    print(f"Scenario {i+1}: p={p} -> Loss = {loss:.4f}")

# Verify with sklearn (log_loss is cross-entropy)
sklearn_loss = log_loss(y_true_binary, y_pred_proba, labels=[0, 1])
print(f"\nSklearn average log loss: {sklearn_loss:.4f}")
print(f"Manual average loss: {np.mean(manual_losses):.4f}")

# Show the penalty ratio
print(f"\nPenalty ratio (p=0.1 vs p=0.9): {manual_losses[2] / manual_losses[0]:.1f}x")
print("Interpretation: Being 90% confident and wrong costs over 20x more than being 90% confident and right.")

For multi-class classification (more than two categories—think dog vs. cat vs. bird), the idea is identical. The formula sums over all classes, but only the term for the true class contributes to the penalty:

L = -Σ (y_true_class * log(p_pred_class))

Since y_true_class is 1 for the correct class and 0 for all others, this just says: “Take the negative log of the probability you assigned to the right answer.” That’s it. The math looks scarier with the summation, but the intuition is exactly the same.

Why is cross-entropy the “natural” classification loss? Because minimizing cross-entropy is mathematically equivalent to maximizing the likelihood of the data under your model—in other words, finding the model that makes the observed labels most probable. This is why you’ll see it used almost universally for classification.

Why Not MSE for Classification? A Cautionary Tale

At this point, you might be wondering: “If MSE works for regression, why can’t I just use it for classification? A wrong prediction is a wrong prediction, right?”

Let’s see what happens when you try. We’ll train a simple classifier on a synthetic binary dataset, once with cross-entropy and once with MSE, and watch how they behave.

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import log_loss, mean_squared_error, accuracy_score
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

# Create a synthetic binary classification dataset
X, y = make_classification(n_samples=1000, n_features=5, n_informative=3, 
                           n_redundant=1, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Scale the features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# Train two models: one with log loss (cross-entropy), one with squared error (MSE)
# SGDClassifier uses 'log_loss' for logistic regression (cross-entropy)
model_ce = SGDClassifier(loss='log_loss', max_iter=1, learning_rate='constant', 
                          eta0=0.01, random_state=42, warm_start=True)
# For MSE, we use 'squared_error' loss
model_mse = SGDClassifier(loss='squared_error', max_iter=1, learning_rate='constant', 
                           eta0=0.01, random_state=42, warm_start=True)

# Track losses during training
ce_losses = []
mse_losses = []
ce_accuracies = []
mse_accuracies = []

n_epochs = 200
for epoch in range(n_epochs):
    # Partial fit for one epoch
    model_ce.partial_fit(X_train_scaled, y_train, classes=np.array([0, 1]))
    model_mse.partial_fit(X_train_scaled, y_train, classes=np.array([0, 1]))
    
    # Get predicted probabilities for loss calculation
    proba_ce = model_ce.predict_proba(X_train_scaled)
    proba_mse = model_mse.predict_proba(X_train_scaled)
    
    # Calculate losses
    ce_loss = log_loss(y_train, proba_ce)
    mse_loss = mean_squared_error(y_train, proba_mse[:, 1])
    
    ce_losses.append(ce_loss)
    mse_losses.append(mse_loss)
    
    # Calculate accuracies
    ce_acc = accuracy_score(y_train, model_ce.predict(X_train_scaled))
    mse_acc = accuracy_score(y_train, model_mse.predict(X_train_scaled))
    ce_accuracies.append(ce_acc)
    mse_accuracies.append(mse_acc)

# Plot the loss curves
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))

ax1.plot(ce_losses, label='Cross-Entropy Loss', color='#2ecc71', linewidth=2)
ax1.plot(mse_losses, label='MSE Loss', color='#e74c3c', linewidth=2)
ax1.set_xlabel('Epoch', fontsize=12)
ax1.set_ylabel('Loss', fontsize=12)
ax1.set_title('Training Loss Over Time', fontsize=14, fontweight='bold')
ax1.legend(fontsize=11)
ax1.grid(True, alpha=0.3)
ax1.annotate('MSE barely moves\nwhen model is wrong', xy=(10, mse_losses[10]), 
            xytext=(50, mse_losses[10] + 0.02),
            arrowprops=dict(arrowstyle='->', color='#e74c3c'),
            fontsize=10, color='#e74c3c')

ax2.plot(ce_accuracies, label='Cross-Entropy Accuracy', color='#2ecc71', linewidth=2)
ax2.plot(mse_accuracies, label='MSE Accuracy', color='#e74c3c', linewidth=2)
ax2.set_xlabel('Epoch', fontsize=12)
ax2.set_ylabel('Accuracy', fontsize=12)
ax2.set_title('Training Accuracy Over Time', fontsize=14, fontweight='bold')
ax2.legend(fontsize=11)
ax2.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

# Print final comparison
print(f"Final Cross-Entropy Accuracy: {ce_accuracies[-1]:.3f}")
print(f"Final MSE Accuracy: {mse_accuracies[-1]:.3f}")
print(f"\nCross-Entropy converged to low loss in ~{next(i for i, l in enumerate(ce_losses) if l < 0.5)} epochs")

What you’ll see is striking. The cross-entropy model’s loss drops quickly and steadily. The MSE model’s loss barely budges, especially in the early epochs when the model is making big mistakes.

Why does this happen? There are two reasons, and understanding them is the key to understanding why cross-entropy owns classification.

The gradient problem. When a classifier is very wrong—say it outputs a probability of 0.01 for the true class—the sigmoid function that produced that probability is in a “saturated” region. The gradient (the nudge the model gets) is tiny. MSE doesn’t fix this; it just passes the tiny gradient through. Cross-entropy, however, mathematically cancels out the sigmoid’s saturation. When the model is confidently wrong, cross-entropy gives a strong learning signal—exactly when the model needs it most. This is why cross-entropy converges so much faster.

The probabilistic mismatch. MSE assumes your errors are normally distributed around a continuous true value. That makes sense for house prices. But classification errors are Bernoulli—you’re either right or wrong, and the probability of being right is exactly what the model outputs. Cross-entropy is derived directly from this Bernoulli assumption. Using MSE for classification is like using a ruler designed for measuring length to measure temperature—it kind of works, but it’s fighting the physics of the problem.

This is the hardest part of classification loss: understanding why the math of cross-entropy “undoes” the sigmoid saturation. You don’t need to memorize the derivative. You just need to remember: cross-entropy yells loudest when the model is confidently wrong, and that’s exactly when the model needs the strongest correction.

The Complete Reference Table

Here’s everything we’ve learned, consolidated into a single reference. This is the table to screenshot and come back to when you’re staring at a new problem and wondering which loss function to use.

Loss FunctionFormula (Plain English)Best ForAvoid WhenPyTorchsklearn
MSE (Mean Squared Error)Average of (actual - predicted)². Squaring makes all errors positive and heavily punishes large ones.Regression where large errors are unacceptable (medical, safety-critical). Data is clean, outliers are rare.Your data has significant outliers that you don’t want to dominate training.torch.nn.MSELoss()sklearn.metrics.mean_squared_error
MAE (Mean Absolute Error)Average ofactual - predicted. Absolute value makes errors positive without amplification.Regression with noisy data or outliers (real estate, sensor data, user behavior). You want a model that captures the typical pattern.Large errors are genuinely critical and you need the model to prioritize them.
Binary Cross-Entropy-[y·log(p) + (1-y)·log(1-p)]. Penalizes low probability assigned to the true class. Being confidently wrong is the worst crime.Binary classification (spam/ham, yes/no). Model outputs a probability between 0 and 1.Regression problems (predicting continuous numbers).torch.nn.BCELoss() (after sigmoid) or torch.nn.BCEWithLogitsLoss() (combined)sklearn.metrics.log_loss
Categorical Cross-Entropy-Σ(y_true_class · log(p_pred_class)). Sum over all classes; only the true class contributes. Same intuition as binary, extended to multiple classes.Multi-class classification (dog/cat/bird). Model outputs a probability distribution over classes.Binary classification (use binary cross-entropy instead, though categorical works too).torch.nn.CrossEntropyLoss() (combines LogSoftmax + NLLLoss—don’t apply softmax first)sklearn.metrics.log_loss

Quick decision heuristic:

  • Predicting a number? → MSE or MAE. Outliers matter? MSE. Outliers are noise? MAE.
  • Predicting a category? → Cross-entropy. Always. Don’t use MSE for classification.

Recap and What’s Next

Let’s land this plane. Here’s what we’ve learned:

  • MSE squares errors and punishes outliers heavily. Use it when large mistakes are genuinely unacceptable—the model will move mountains to avoid them.
  • MAE takes absolute errors and treats all mistakes proportionally. Use it when your data is messy and you don’t want outliers hijacking the training process.
  • Cross-entropy measures how wrong your predicted probabilities are. It screams loudest when the model is confidently wrong, which is exactly when the model needs the strongest correction. Use it for classification, always.

The meta-lesson is this: the loss function isn’t just a scorecard. It’s the steering wheel. It defines what “good” means for your model, and choosing the right one is one of the most consequential decisions you’ll make.

Now that you know how to measure wrongness, the next question is: how do you prevent your model from memorizing the training data instead of learning general patterns? That’s where regularization comes in—and that’s exactly what we’ll tackle next.

Check Your Understanding

Test yourself against these six questions, moving from simple recall to creative application.

Remember: What does MSE stand for, and what’s the formula?

Understand: In your own words, why does MSE punish outliers more than MAE?

Apply: A dataset of city temperatures has a few sensor-malfunction readings of 999°F. Which loss function would you choose for a regression model, and why?

Analyze: A binary classifier outputs a probability of 0.99 for the correct class. Calculate the cross-entropy loss. Now calculate it for a probability of 0.51. Why is the difference so large?

Evaluate: A colleague uses MSE to train an image classifier “because it’s simpler.” Give two concrete reasons why this is a bad idea.

Create: Design a loss function for a problem where errors in one direction are 10 times more costly than errors in the other direction (e.g., predicting inventory demand—overstocking costs more than understocking). What would your formula look like?

Apply What You Learned

Task: Take the California Housing dataset (available via sklearn.datasets.fetch_california_housing), train two linear regression models—one with MSE and one with MAE—and compare their predictions on the most expensive houses.

Deliverable: A short Jupyter notebook containing:

  1. Both trained models.
  2. A scatter plot of predictions vs. actual values for the top 10% most expensive houses, with both models’ predictions overlaid in different colors.
  3. A paragraph explaining which loss function you’d choose for a real-estate pricing app and why, connecting your reasoning back to the outlier-sensitivity concepts from this article.

Self-check rubric:

  • Did you correctly identify that MAE is less influenced by the high-end outliers?
  • Does your plot show the MSE model “chasing” the expensive houses more aggressively?
  • Does your explanation connect back to the core trade-off (MSE amplifies large errors, MAE treats them proportionally)?

Looking for something else?

Search every article by title, summary or topic.