Likelihood: Where Loss Functions Come From
Read PMFs and PDFs of the Bernoulli, binomial, Poisson and normal distributions, define the likelihood and its maximum, derive mean squared error from Gaussian noise, mean absolute error from Laplace noise and log-loss from a Bernoulli label, and see how a prior turns MLE into MAP and regularisation.
Contentsand lesson path
On this page
- Why it matters
- PMFs, PDFs and four common distributions
- Likelihood and the maximum likelihood estimate
- From a noise model to a regression loss
- From a Bernoulli label to log-loss
- MLE versus MAP: adding a prior
- Check your understanding
- Apply it
- Review prompt
Lessons of Probability & Statistics for ML
- Describing Data: Statistics and Plots for Spread, Shape and Imbalance Concept · 25 min
- Conditional Probability and the Base-Rate Trap Concept · 20 min
- Likelihood: Where Loss Functions Come From Concept · 25 min
- Lab: Bootstrap a Confidence Interval for a Model Metric Lab · 30 min
- Worked Example: Is Model B Really Better Than Model A? Worked example · 20 min
- Check: Reasoning Under Uncertainty Knowledge check · 8 questions
What you will learn
- Explain maximum likelihood estimation and derive how it leads to squared-error and log-loss objectives.
01. Why it matters
You train regression models with mean squared error and classifiers with log-loss, often because that is the default. These losses are not arbitrary. Each one is what you get when you write down a probability model for how the labels were generated and then pick the parameters that make the observed labels most probable. That method is called maximum likelihood estimation (MLE).
Knowing where a loss comes from tells you when it fits. If your targets contain occasional huge errors, the squared error assumes a noise model that rarely produces them, and a different assumption gives a more robust loss. If you have little data, adding a prior belief gives MAP estimation, which turns out to be the same thing as regularisation. The examples were tested with Python 3.12, NumPy 2.5, SciPy 1.18 and scikit-learn 1.9.
02. PMFs, PDFs and four common distributions
A probability model starts with a distribution: a rule that says how likely each value of a random variable is. For a discrete variable, which takes separate values such as 0, 1, 2, the rule is a probability mass function (PMF): P(X = k) for each k, and these probabilities add up to 1. For a continuous variable, such as a measurement error, any single exact value has probability 0, so the rule is a probability density function (PDF). A probability is the area under the density over an interval, and the density itself can be larger than 1.
Four distributions cover many machine-learning cases:
- Bernoulli(p): one yes/no outcome, 1 with probability p. Mean p, variance p(1 − p). Example: one click.
- Binomial(n, p): the number of 1s in n independent Bernoulli trials. Mean np, variance np(1 − p). Example: clicks in 10 views.
- Poisson(μ): the number of events in a fixed interval when they happen independently at an average rate μ. Mean and variance are both μ. Example: support tickets per hour.
- Normal(μ, σ): the bell curve, with mean μ and standard deviation σ. Sums of many small independent effects tend towards it, which is why measurement errors often look normal.
SciPy gives each distribution the same methods: pmf or pdf, cdf (the probability of a value at or below a point) and stats for the mean and variance.
"""Four common distributions in scipy.stats: probabilities, densities, moments."""
from scipy import stats
dists = {
"Bernoulli(p=0.3)": stats.bernoulli(0.3), # one click: 1 or 0
"binomial(n=10, p=0.3)": stats.binom(10, 0.3), # clicks in 10 views
"Poisson(mu=4)": stats.poisson(4), # tickets arriving in one hour
"normal(mu=0, sd=0.1)": stats.norm(0, 0.1), # a measurement error
}
for name, d in dists.items():
mean, var = d.stats(moments="mv")
print(f"{name:<22} mean {float(mean):5.2f} variance {float(var):5.2f}")
print(f"P(3 clicks in 10 views) = {stats.binom.pmf(3, 10, 0.3):.3f}")
print(f"P(2 tickets in an hour) = {stats.poisson.pmf(2, 4):.3f}")
print(f"normal density at 0 = {stats.norm.pdf(0, 0, 0.1):.3f}")
print(f"P(-0.1 < error < 0.1) = "
f"{stats.norm.cdf(0.1, 0, 0.1) - stats.norm.cdf(-0.1, 0, 0.1):.3f}")Bernoulli(p=0.3) mean 0.30 variance 0.21
binomial(n=10, p=0.3) mean 3.00 variance 2.10
Poisson(mu=4) mean 4.00 variance 4.00
normal(mu=0, sd=0.1) mean 0.00 variance 0.01
P(3 clicks in 10 views) = 0.267
P(2 tickets in an hour) = 0.147
normal density at 0 = 3.989
P(-0.1 < error < 0.1) = 0.683The normal density at 0 is 3.989, well above 1, and that is fine: the curve is narrow, so the area under it is still 1. The probability of an error between −0.1 and 0.1, one standard deviation either side, is the area 0.683, the familiar 68%.
03. Likelihood and the maximum likelihood estimate
A model with a parameter θ (theta) gives a probability to any dataset: P(data | θ). Hold the data fixed, vary θ, and the same formula becomes the likelihood L(θ): how well each parameter value explains what you saw. The likelihood is not a probability distribution over θ; it does not need to sum to 1 across θ.
For independent observations the likelihood is a product of one term per observation, which quickly becomes too small for a computer to store. So we work with the log-likelihood, a sum of logs. The logarithm is an increasing function, so the θ that maximises the log-likelihood also maximises the likelihood. Take 7 clicks in 20 views, modelled as Bernoulli trials with click rate p.
"""Maximum likelihood for a click rate: search a grid of p for 7 clicks in 20 views."""
import numpy as np
clicks = np.array([1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0])
k, n = clicks.sum(), clicks.size
def log_likelihood(p):
# log of p^k (1 - p)^(n - k): a sum of logs instead of a product of tiny numbers
return k * np.log(p) + (n - k) * np.log(1 - p)
for p in [0.2, 0.35, 0.5]:
print(f"p = {p:.2f} likelihood {np.exp(log_likelihood(p)):.2e} "
f"log-likelihood {log_likelihood(p):7.3f}")
grid = np.linspace(0.001, 0.999, 999)
best = grid[np.argmax(log_likelihood(grid))]
print(f"grid maximum at p = {best:.3f}; k / n = {k / n:.3f}")p = 0.20 likelihood 7.04e-07 log-likelihood -14.167
p = 0.35 likelihood 2.38e-06 log-likelihood -12.949
p = 0.50 likelihood 9.54e-07 log-likelihood -13.863
grid maximum at p = 0.350; k / n = 0.350Even the best likelihood is tiny (2.38e-06), because it is the probability of this exact sequence of 20 outcomes. Only the comparison between parameter values matters. The grid search finds the maximum at p = 0.35, exactly k / n. Calculus gives the same answer: the derivative of k log p + (n − k) log(1 − p) is zero when p = k / n. For a Poisson model of counts, the same steps show that the MLE of the rate μ is the mean of the observed counts.
04. From a noise model to a regression loss
In regression, assume each target is the model's prediction plus random noise: y = ŷ + ε. If ε is Gaussian (normal) with mean 0 and a fixed standard deviation σ, the density of one target is proportional to exp(−(y − ŷ)² / 2σ²). Take the negative log and sum over n examples:
- −log L = n log σ + (n / 2) log 2π + Σ (y − ŷ)² / 2σ²
Only the last term depends on the model's parameters, and σ is a positive constant there. So maximising the Gaussian likelihood is the same as minimising the sum of squared errors, and therefore the mean squared error (MSE). The script fits a line both ways.
"""Maximise a Gaussian likelihood and compare with least squares; then try Laplace."""
import numpy as np
from scipy import optimize
from sklearn.linear_model import LinearRegression
rng = np.random.default_rng(2)
x = rng.uniform(0, 10, size=200)
y = 4.0 + 2.5 * x + rng.normal(0, 1.5, size=200) # line plus Gaussian noise
def gaussian_nll(params):
b0, b1, log_sd = params # log_sd keeps the standard deviation positive
sd = np.exp(log_sd)
resid = y - (b0 + b1 * x)
return np.sum(np.log(sd) + 0.5 * np.log(2 * np.pi) + resid**2 / (2 * sd**2))
b0, b1, log_sd = optimize.minimize(gaussian_nll, x0=[0.0, 0.0, 0.0]).x
ols = LinearRegression().fit(x.reshape(-1, 1), y)
mse = np.mean((y - ols.predict(x.reshape(-1, 1))) ** 2)
print(f"max likelihood: intercept {b0:.3f} slope {b1:.3f} sd {np.exp(log_sd):.3f}")
print(f"least squares: intercept {ols.intercept_:.3f} slope {ols.coef_[0]:.3f} "
f"sqrt(MSE) {np.sqrt(mse):.3f}")
# One constant prediction c for delivery times that include two very late orders
times = np.array([31, 29, 35, 33, 30, 28, 34, 95, 120], dtype=float)
def nll_gauss(c, sd=10.0): # the scale is fixed: it does not move the best c
return np.sum(0.5 * np.log(2 * np.pi * sd**2) + (times - c) ** 2 / (2 * sd**2))
def nll_laplace(c, b=10.0):
return np.sum(np.log(2 * b) + np.abs(times - c) / b)
for name, nll, ref in [("Gaussian", nll_gauss, f"mean {times.mean():.2f}"),
("Laplace", nll_laplace, f"median {np.median(times):.2f}")]:
best = optimize.minimize_scalar(nll, bounds=(0, 150), method="bounded").x
print(f"{name:<8} MLE of c {best:6.2f} ({ref})")max likelihood: intercept 4.006 slope 2.483 sd 1.583
least squares: intercept 4.006 slope 2.483 sqrt(MSE) 1.583
Gaussian MLE of c 48.33 (mean 48.33)
Laplace MLE of c 33.00 (median 33.00)The maximum-likelihood line and the least-squares line agree to three decimals, and the MLE of σ equals the square root of the MSE. Now swap the noise model. Laplace noise has density proportional to exp(−|y − ŷ| / b), with a sharper peak and heavier tails, so large errors are more plausible. Its negative log-likelihood is n log 2b + Σ |y − ŷ| / b, so maximising it means minimising the mean absolute error (MAE).
The second half of the script shows the consequence for the simplest model, one constant c for every row. The Gaussian MLE of c is the mean, 48.33, dragged up by the two very late orders. The Laplace MLE is the median, 33.00, which ignores how extreme those two are. Choosing a loss is choosing a noise model: if rare, huge errors are part of your data, MAE (or a compromise such as the Huber loss) fits that belief better than MSE.
05. From a Bernoulli label to log-loss
A binary classifier outputs p, its estimate of P(y = 1). Model the label as Bernoulli(p): the likelihood of one label is p^y (1 − p)^(1 − y), which is p when y = 1 and 1 − p when y = 0. The negative log-likelihood per example is −[y log p + (1 − y) log(1 − p)], better known as log-loss or binary cross-entropy. Training a logistic regression or a neural-network classifier with this loss is maximum likelihood.
"""The Bernoulli negative log-likelihood, by hand and with scikit-learn."""
import numpy as np
from sklearn.metrics import log_loss
y = np.array([1, 0, 1, 1, 0])
p = np.array([0.9, 0.2, 0.6, 0.95, 0.7]) # predicted P(y = 1) for each example
likelihood = p**y * (1 - p) ** (1 - y) # p when y = 1, and 1 - p when y = 0
nll = -np.log(likelihood)
for yi, pi, li in zip(y, p, nll):
print(f"y = {yi} p = {pi:.2f} -log likelihood {li:.3f}")
print(f"mean by hand {nll.mean():.4f} sklearn log_loss {log_loss(y, p):.4f}")
# One confident mistake: log-loss grows without limit, squared error stops at 1
print(f"y = 0, p = 0.99: -log likelihood {-np.log(1 - 0.99):.3f} "
f"squared error {(0 - 0.99) ** 2:.3f}")y = 1 p = 0.90 -log likelihood 0.105
y = 0 p = 0.20 -log likelihood 0.223
y = 1 p = 0.60 -log likelihood 0.511
y = 1 p = 0.95 -log likelihood 0.051
y = 0 p = 0.70 -log likelihood 1.204
mean by hand 0.4189 sklearn log_loss 0.4189
y = 0, p = 0.99: -log likelihood 4.605 squared error 0.980The hand computation matches sklearn.metrics.log_loss. Look at the per-example values: confident correct predictions cost little (0.051), and the one confident mistake (p = 0.70 for a 0) costs more than the other four together. At p = 0.99 for a 0 the cost is 4.605, and it grows without limit as p approaches 1, while the squared error can never exceed 1. Log-loss therefore punishes overconfidence hard, which is why it rewards calibrated probabilities. scikit-learn clips probabilities just inside 0 and 1, so a prediction of exactly 0 or 1 gives a very large loss instead of infinity. With more than two classes the same derivation, with a categorical distribution, gives categorical cross-entropy. Not every loss is a likelihood in disguise: the hinge loss of support vector machines comes from maximising the margin between classes, not from a noise model.
06. MLE versus MAP: adding a prior
MLE trusts the data completely. A new advert with 3 clicks in 3 views gets an MLE click rate of 1.0, which nobody believes. Maximum a posteriori (MAP) estimation adds what you knew beforehand. By Bayes' rule, P(θ | data) is proportional to P(data | θ) × P(θ), so MAP maximises the log-likelihood plus the log of a prior P(θ). For a rate, a convenient prior is the Beta(a, b) distribution, and the MAP estimate then has a closed form: (k + a − 1) / (n + a + b − 2).
"""MLE versus MAP for a click rate, with a Beta(2, 18) prior."""
import numpy as np
from scipy import optimize, stats
prior = stats.beta(2, 18) # earlier ads: rates mostly between 2% and 23%
lo, hi = prior.ppf([0.05, 0.95])
print(f"prior: mode {1 / 18:.3f}, 90% of its mass between {lo:.3f} and {hi:.3f}")
def best(objective):
return optimize.minimize_scalar(objective, bounds=(1e-9, 1 - 1e-9),
method="bounded", options={"xatol": 1e-9}).x
for k, n in [(3, 3), (30, 300)]: # clicks, views
def nll(p):
return -(k * np.log(p) + (n - k) * np.log(1 - p))
mle = best(nll)
map_ = best(lambda p: nll(p) - prior.logpdf(p)) # add the negative log prior
print(f"{k:>2} clicks in {n:>3} views: MLE {mle:.3f} MAP {map_:.3f} "
f"(formula {(k + 1) / (n + 18):.3f})")prior: mode 0.056, 90% of its mass between 0.019 and 0.226
3 clicks in 3 views: MLE 1.000 MAP 0.190 (formula 0.190)
30 clicks in 300 views: MLE 0.100 MAP 0.097 (formula 0.097)With 3 views, the prior pulls the estimate from 1.0 down to 0.190. With 300 views the data dominate and MAP (0.097) is close to MLE (0.100). That is the general pattern: a prior matters most when data are scarce.
The same idea explains regularisation. Put a Gaussian prior with mean 0 on every weight of a linear model, and the negative log prior is a constant plus Σ w² / 2τ², where τ is the prior's standard deviation. MAP then minimises squared error plus an L2 penalty: that is ridge regression, or weight decay in a neural network. A Laplace prior on the weights gives an L1 penalty, as in the lasso. MAP still returns a single best value; full Bayesian inference keeps the whole posterior distribution.
07. Check your understanding
08. Apply it
For the two classifiers in this skill's practice task:
- Compute each model's log-loss on the test set with
log_loss, and list the five rows with the largest per-row loss. Check whether they are confident mistakes. - Compare the ranking of the two models by log-loss with their ranking by F1. If they disagree, write one sentence on why: F1 only looks at the predicted labels, log-loss at the probabilities behind them.
- Keep the per-row losses. Lesson 5 compares models with a paired bootstrap, and the same method works for a mean of per-row losses.
09. Review prompt
Without looking back:
- What is the difference between a PMF and a PDF, and why can a density exceed 1?
- What is the likelihood, and why do we maximise its logarithm?
- Derive the loss that follows from Gaussian noise, from Laplace noise and from a Bernoulli label.
- How does MAP differ from MLE, and which prior leads to an L2 penalty?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.