Block 4.2 Advanced AI
\[ \text{model family} \quad \model{\vect{x}} \qquad\Longrightarrow\qquad \text{training criterion} \quad \loss[\params] \]
By the end of this lecture, you should be able to:
Assume a training dataset
\[ \set{D}=\{(\vect{x}_i,y_i)\}_{i=1}^{I}. \]
A loss function assigns a scalar score to a parameter setting:
\[ \loss[\params]\in\reals, \qquad \hat{\params} = \argmin_{\params} \loss[\params]. \]
A loss function scores every candidate parameter setting. Training wants the parameter value at the bottom of the loss landscape.
A one-dimensional loss landscape. \(\hat{\phi}\) is the parameter value at the minimum.
For real-valued regression, a familiar choice is
\[ \loss[\params] = \sum_{i=1}^{I} \left(y_i-\model{\vect{x}_i}\right)^2. \]
Question: why this loss — and what should we use for other output types?
| Task | Output domain | Example |
|---|---|---|
| Regression | \(y\in\reals\) | temperature |
| Binary classification | \(y\in\{0,1\}\) | spam / not spam |
| Multiclass classification | \(y\in\{1,\ldots,K\}\) | object category |
| Count prediction | \(y\in\{0,1,2,\ldots\}\) | number of arrivals |
| Direction | \(y\in(-\pi,\pi]\) | orientation angle |
Suppose two weather models both predict
\[ \hat y = 20^\circ\mathrm{C}. \]
The same point estimate can still represent very different uncertainty:
Two Gaussian predictive distributions with mean \(20^\circ\mathrm{C}\) and different variances.
\[ \boxed{\text{same point estimate} \;\not\Rightarrow\; \text{same uncertainty}} \]
A point-prediction view returns one number:
\[ \hat y=\model{\vect{x}}. \]
A probabilistic view returns the parameters of a distribution:
\[ \distparams =\model{\vect{x}}, \qquad y\sim p(y\mid\distparams). \]
The network remains deterministic; its output parameterises a predictive distribution over \(y\).
Predictive distributions at two input values for regression, classification, count, and directional targets.
A probability distribution is not an arbitrary curve the network must draw from scratch.
Choose a distribution family, then let its parameters act as adjustable knobs:
| Distribution | Parameters | What the parameters control |
|---|---|---|
| Normal | \(\mu,\sigma^2\) | centre and spread |
| Bernoulli | \(\lambda\) | probability of class \(1\) |
| Categorical | \(\lambda_1,\ldots,\lambda_K\) | probability allocated to each class |
In general,
\[ p(y\mid\distparams), \qquad \distparams_i=\model{\vect{x}_i}. \]
Think of a distribution as having one unit of probability to allocate.
Discrete outcomes: split that unit among separate possibilities.
\[ \sum_y p(y)=1. \]
A bar height is itself a probability.
Continuous outcomes: spread that unit across a continuum.
\[ \int p(y)\,dy=1. \]
Probability is now an area under the density curve, not the height at one point.
A narrow density can rise above \(1\) without violating probability rules; its total area is still \(1\).
Consider a continuous variable that is uniform on the interval \([0,0.5]\).
Uniform density on \([0,0.5]\): height \(2\), width \(0.5\), total area \(1\).
A random variable represents a quantity whose value is uncertain. Its distribution describes which values are plausible and how strongly they are weighted.
Discrete random variable
Continuous random variable
Maximum likelihood scores an observed discrete value by its probability mass and an observed continuous value by its density.
For one training example, we will repeatedly write
\[ p\!\left(y_i\mid \model{\vect{x}_i}\right). \]
Read it from the inside out:
In words: given input \(\vect{x}_i\) and the current network parameters \(\params\), how much probability mass or density does the resulting predictive distribution assign to the observed target \(y_i\)?
Equivalently, using \(\distparams_i=\model{\vect{x}_i}\),
\[ \vect{x}_i \longrightarrow \distparams_i \longrightarrow p(y\mid\distparams_i) \longrightarrow p(y_i\mid\distparams_i). \]
Suppose
\[ P(Y=0)=0.2, \qquad P(Y=1)=0.5, \qquad P(Y=2)=0.3. \]
The expected value is
\[ \expect{Y} = 0(0.2)+1(0.5)+2(0.3) = 1.1. \]
Expectation means “average according to this distribution.”
For a function \(g(Y)\), expectation averages the value of \(g\) using the probabilities of \(Y\) as weights.
Discrete: \[ \expectsub{Y\sim q}{g(Y)} = \sum_y g(y)q(y). \]
Continuous: \[ \expectsub{Y\sim q}{g(Y)} = \int g(y)q(y)\,dy. \]
For one training pair \((\vect{x}_i,y_i)\), define the model score for what actually happened:
\[ p_i = p\!\left(y_i\mid \model{\vect{x}_i}\right). \]
The rule will come from an independence assumption.
Start with two independent fair coin tosses.
\[ P(H,H) = P(H)P(H) = \frac12\times\frac12 = \frac14. \]
Why multiply?
For independent variables in general,
\[ p(a,b)=p(a)p(b). \]
For all training targets together, the model concerns the joint distribution
\[ p(y_1,\ldots,y_I\mid\vect{x}_1,\ldots,\vect{x}_I). \]
The standard supervised-learning model assumes the targets are conditionally independent once their inputs are given:
\[ p(y_1,\ldots,y_I\mid\vect{x}_1,\ldots,\vect{x}_I) = \prod_{i=1}^{I}p(y_i\mid\vect{x}_i). \]
This factorisation is a modelling assumption, not a property of neural networks.
Apply the same factorisation to the per-example scores \(p_i\):
\[ \likelihood(\params;\set{D}) = \prod_{i=1}^{I}p_i = \prod_{i=1}^{I} p\!\left(y_i\mid \model{\vect{x}_i}\right). \]
Read the product as:
\(\likelihood\) is the likelihood function for the model parameters, with the observed dataset held fixed.
The vertical bar in
\[ p(y\mid\vect{x},\params) \]
is read “\(y\) given \(\vect{x}\) and \(\params\)”: it describes uncertainty in \(y\) once the conditioning quantities are fixed.
The same expression has two roles.
Vary \(y\); fix \(\vect{x},\params\)
Fix the observed \(y,\vect{x}\); vary \(\params\)
Fixing the parameters gives a density over outcomes; fixing the observation gives a likelihood as the parameter varies.
Choose parameters that make the observed dataset as likely as possible:
\[ \hat{\params} = \argmax_{\params} \likelihood(\params;\set{D}) = \argmax_{\params} \prod_{i=1}^{I}p_i. \]
Equivalently,
\[ \hat{\params} = \argmax_{\params} \prod_{i=1}^{I} p\!\left(y_i\mid \model{\vect{x}_i}\right). \]
This is the maximum-likelihood criterion.
Products of many small probability values can underflow numerically:
\[ 0.01\times0.02\times0.03\times\cdots \]
Product of repeated probability factors compared with the corresponding sum of log-probabilities.
The logarithm solves this without changing which parameters are best.
Because \(\log\) is strictly increasing for positive arguments,
\[ a>b>0 \quad\Longleftrightarrow\quad \log a>\log b. \]
Therefore
\[ \argmax_{\params} \likelihood(\params;\set{D}) = \argmax_{\params} \log\likelihood(\params;\set{D}). \]
A positive function and its logarithm. The scale changes; the maximiser does not.
Use the identity
\[ \log\!\left(\prod_i a_i\right) = \sum_i\log a_i. \]
Then
\[ \begin{aligned} \log\likelihood(\params;\set{D}) &= \log\!\left(\prod_{i=1}^{I}p_i\right)\\[4pt] &= \sum_{i=1}^{I}\log p_i\\[4pt] &= \sum_{i=1}^{I} \log p\!\left(y_i\mid \model{\vect{x}_i}\right). \end{aligned} \]
Training is conventionally written as a minimisation problem.
Maximising log-likelihood is equivalent to minimising its negative:
\[ \boxed{ \hat{\params} = \argmax_{\params}\likelihood = \argmax_{\params}\log\likelihood = \argmin_{\params}[-\log\likelihood] } \]
So define the negative log-likelihood:
\[ \loss[\params] = -\sum_{i=1}^{I} \log p\!\left(y_i\mid \model{\vect{x}_i}\right). \]
Define one example’s contribution as
\[ \exloss_i(\params) = -\log p\!\left(y_i\mid \model{\vect{x}_i}\right). \]
Then
\[ \loss[\params] = \sum_{i=1}^{I}\exloss_i(\params). \]
Implementations often minimise the mean instead:
\[ \erisk[\params] = \frac{1}{I}\sum_{i=1}^{I}\exloss_i(\params). \]
For a discrete observed target with probability mass \(p\),
\[ \boxed{\exloss=-\log p} \]
This quantity is often read as surprise:
| Probability assigned to what happened | Surprise \(-\log p\) |
|---|---|
| \(1\) | \(0\) |
| \(0.5\) | \(0.693\) |
| \(0.1\) | \(2.303\) |
| \(0.01\) | \(4.605\) |
\[ \boxed{\text{training chooses parameters that make the observed data as unsurprising as possible}} \]
Continuous case: use probability density rather than mass. A density may exceed \(1\), so an individual continuous NLL contribution can be negative; the optimisation principle is unchanged.
Suppose two parameter settings assign these probabilities to the correct class labels:
| Example 1 | Example 2 | Example 3 | Likelihood | NLL | |
|---|---|---|---|---|---|
| Model A | \(0.8\) | \(0.7\) | \(0.6\) | \(0.336\) | \(\approx1.09\) |
| Model B | \(0.9\) | \(0.2\) | \(0.9\) | \(0.162\) | \(\approx1.82\) |
\[ 0.336>0.162 \qquad\Longleftrightarrow\qquad 1.09<1.82. \]
Training
\[ \hat{\params} = \argmin_{\params}\loss[\params]. \]
Inference
\[ p\!\left(y\mid \model[\hat{\params}]{\vect{x}}\right) \]
The predictive distribution is the model output in probabilistic form; a point estimate is an additional decision rule.
One common choice is the mode:
\[ \hat y_{\text{mode}} = \argmax_{y} p\!\left(y\mid \model[\hat{\params}]{\vect{x}}\right). \]
But the appropriate point estimate depends on what error or downstream decision matters:
For a normal distribution these coincide:
\[ y\mid\vect{x}\sim\normal(\mu,\sigma^2) \quad\Longrightarrow\quad \text{mean}=\text{median}=\text{mode}=\mu. \]
“The network predicts a distribution, not a value.”
The network predicts distribution parameters; a decision rule can still produce a point estimate.
“Likelihood is the probability of the parameters.”
No. The observed data are fixed; likelihood scores candidate parameter settings.
“Taking logs changes the best parameters.”
No. A strictly increasing transform preserves their ordering and hence the optimum.
“NLL is just negative probability.”
No. It is the negative logarithm of the probability mass or density assigned to the observation.
\[ \boxed{ \loss[\params] = -\sum_{i=1}^{I} \log p\!\left(y_i\mid \model{\vect{x}_i}\right) } \]
For training data
\[ \set{D}=\{(\vect{x}_i,y_i)\}_{i=1}^{I}, \]
construct the loss as follows:
Steps 1–2 specify the statistical model; step 3 induces the training loss; step 4 specifies what is returned at prediction time.
Four-step loss construction for regression, binary classification, and multiclass classification.
For each training example,
\[ \distparams_i=\model{\vect{x}_i}. \]
The computation for one example is
\[ \vect{x}_i \longrightarrow \distparams_i \longrightarrow p(y_i\mid\distparams_i) \longrightarrow -\log p(y_i\mid\distparams_i) \longrightarrow \exloss_i. \]
Sum those surprises over the dataset:
\[ \boxed{ \hat{\params} = \argmin_{\params} \left[ -\sum_{i=1}^{I} \log p\!\left(y_i\mid \model{\vect{x}_i}\right) \right] } \tag{5.6} \]
| Modelling question | Task-specific choice |
|---|---|
| What values can \(y\) take? | the target domain |
| How should uncertainty over \(y\) be represented? | the distribution family \(p(y\mid\distparams)\) |
| What must the network output? | one or more parameters \(\distparams\) |
| What loss should be minimised? | the induced NLL \(-\log p(y\mid\distparams)\) |
| What should inference return? | the full distribution or an appropriate point summary |
The domain constrains sensible distribution families; modelling assumptions choose among them.
For a new prediction problem, ask:
The same questions apply across prediction problems; the distribution choice determines the resulting NLL.
Goal: predict a single real-valued target
\[ y\in\reals \]
from an input \(\vect{x}\) using a model with parameters \(\params\).
Following the recipe:
For the first example, choose a univariate normal distribution.
Assume the target is distributed as
\[ y\mid\vect{x}\sim\normal(\mu,\sigma^2). \]
Its probability density is
\[ p(y\mid\mu,\sigma^2) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\!\left[ -\frac{(y-\mu)^2}{2\sigma^2} \right]. \tag{5.7} \]
The Gaussian density can be read as two pieces:
\[ p(y\mid\mu,\sigma^2) = \underbrace{\frac{1}{\sqrt{2\pi\sigma^2}}}_{\text{normalises the total area}} \; \underbrace{\exp\!\left[-\frac12\left(\frac{y-\mu}{\sigma}\right)^2\right]}_{\text{downweights values far from }\mu}. \]
Step by step:
At \(y=\mu\), the squared distance is \(0\) and the density is maximal.
For a random variable \(Y\), the mean is its expectation
\[ \mu=\expect{Y}, \]
and the variance is the expected squared deviation from that mean:
\[ \sigma^2 = \var{Y} = \expect{(Y-\mu)^2}. \]
For \(Y\sim\normal(\mu,\sigma^2)\):
Take four equally weighted observations with mean \(\mu=0\):
Distances from the mean and their squared values for four observations.
\[ \boxed{ \sigma^2 = \expect{(Y-\mu)^2} \;\approx\; \text{average squared distance from the mean} } \]
Normal distributions with different means and standard deviations.
The Gaussian therefore represents both a central prediction and uncertainty around it.
Start with the simplest Gaussian regression model:
\[ \mu=\model{\vect{x}}, \]
while treating \(\sigma^2\) as a fixed constant.
Substituting the predicted mean into the normal density gives
\[ p\!\left(y\mid \model{\vect{x}},\sigma^2\right) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\!\left[ -\frac{\left(y-\model{\vect{x}}\right)^2}{2\sigma^2} \right]. \tag{5.8} \]
For the training set \(\set{D}=\{(\vect{x}_i,y_i)\}_{i=1}^{I}\):
\[ \begin{aligned} \loss[\params] &= -\sum_{i=1}^{I} \log p\!\left(y_i\mid \model{\vect{x}_i},\sigma^2\right)\\[4pt] &= -\sum_{i=1}^{I} \log\!\left\{ \frac{1}{\sqrt{2\pi\sigma^2}} \exp\!\left[ -\frac{\left(y_i-\model{\vect{x}_i}\right)^2}{2\sigma^2} \right] \right\}. \end{aligned} \tag{5.9} \]
Training seeks \(\hat{\params}=\argmin_{\params}\loss[\params]\).
After taking the negative logarithm, one example contributes
\[ \exloss_i = \underbrace{\frac12\log(2\pi\sigma^2)}_{\text{cost of the assumed spread}} + \underbrace{\frac{(y_i-\mu_i)^2}{2\sigma^2}}_{\text{cost of missing the observed value}}. \]
With fixed \(\sigma^2\):
\[ \text{fixed Gaussian variance} \quad\Longrightarrow\quad \text{ranking models by NLL is ranking them by squared error}. \]
Apply \(\log(ab)=\log a+\log b\) and \(\log(e^z)=z\):
\[ \begin{aligned} \hat{\params} &= \argmin_{\params} \sum_{i=1}^{I} \left[ \frac{1}{2}\log(2\pi\sigma^2) + \frac{\left(y_i-\model{\vect{x}_i}\right)^2}{2\sigma^2} \right]\\[6pt] &= \argmin_{\params} \sum_{i=1}^{I} \left(y_i-\model{\vect{x}_i}\right)^2. \end{aligned} \tag{5.10} \]
Why can terms disappear?
The resulting objective is
\[ \boxed{ \loss[\params] = \sum_{i=1}^{I} \left(y_i-\model{\vect{x}_i}\right)^2 } \tag{5.11} \]
Least squares is the maximum-likelihood loss under the assumptions that:
For a fixed \(\sigma^2\):
| Residual view | Probabilistic view |
|---|---|
| \(|y_i-\model{\vect{x}_i}|\) is small | \(y_i\) lies near the Gaussian mean |
| squared residual is small | density assigned to \(y_i\) is high |
| least-squares contribution is small | negative log-likelihood is small |
| poor fit \(\rightarrow\) large squared residual | poor fit \(\rightarrow\) low density at the observation |
\[ \frac{\left(y_i-\mu_i\right)^2}{2\sigma^2} \quad\text{is exactly the data-dependent part of the Gaussian NLL.} \]
Therefore the two criteria rank \(\params\) identically when \(\sigma^2\) is fixed.
The target domain \(y\in\reals\) does not uniquely determine the observation model.
Gaussian and Laplace residual models and their corresponding NLL penalties.
Squared-error and Gaussian-NLL scores for the same two fits. Both criteria rank the left fit better.
After training, the predictive distribution for a new input is
\[ y\mid\vect{x} \sim \normal\!\left( \model[\hat{\params}]{\vect{x}}, \sigma^2 \right). \]
If we want the maximum-density point:
\[ \hat y = \argmax_{y} p\!\left(y\mid \model[\hat{\params}]{\vect{x}},\sigma^2\right) = \model[\hat{\params}]{\vect{x}}. \tag{5.12} \]
For a normal distribution, mean = median = mode, so the familiar regression prediction is recovered.
Least squares discarded \(\sigma^2\) only because it was fixed while optimising \(\params\).
We can instead learn one shared variance jointly with the network:
\[ \boxed{ \hat{\params},\hat\sigma^2 = \argmin_{\params,\sigma^2} \left[ -\sum_{i=1}^{I} \log p\!\left( y_i\mid \model{\vect{x}_i},\sigma^2 \right) \right] } \tag{5.13} \]
Read the optimisation as learning two things from the same likelihood:
At inference:
“Uncertain” can mean two different things.
| Aleatoric | Epistemic | |
|---|---|---|
| Source | randomness or noise in the observation | incomplete knowledge of the model |
| More data? | does not necessarily remove it | can reduce it |
| Example | repeated sensor readings vary | few training examples in this region |
| Modelled by \(\sigma^2\) here? | yes | no |
The Gaussian variance in this section models aleatoric / observation uncertainty: how variable \(y\) remains even when the model parameters are fixed.
A single learned \(\hat\sigma^2\) assumes the same observation-noise level everywhere:
\[ y_i\mid\vect{x}_i \sim \normal\!\left( \model{\vect{x}_i}, \sigma^2 \right). \]
This is homoscedastic regression:
That assumption can be unrealistic when some inputs are intrinsically noisier or less predictable than others.
A constant variance assumes the vertical spread is the same everywhere. Real data can violate that directly.
Synthetic regression data with observation variance that increases with the input.
If uncertainty changes with the input, model it too:
\[ \mu(\vect{x})=\mathrm{f}_1\!\left[\vect{x},\params\right], \qquad s(\vect{x})=\mathrm{f}_2\!\left[\vect{x},\params\right], \qquad \sigma^2(\vect{x})=\exp\!\left(s(\vect{x})\right). \tag{5.14} \]
Now each input gets its own predictive distribution:
\[ y\mid\vect{x} \sim \normal\!\left( \mu(\vect{x}), \sigma^2(\vect{x}) \right). \]
Equation 5.14 uses an unconstrained raw network output
\[ s(\vect{x})=\mathrm{f}_2\!\left[\vect{x},\params\right]\in\reals. \]
A Gaussian variance must instead be strictly positive:
\[ \sigma^2(\vect{x})>0. \]
So the raw score must be transformed before it is used as a variance:
\[ \boxed{ s(\vect{x})\in\reals \quad\longrightarrow\quad \sigma^2(\vect{x})>0 } \]
Common strictly positive parameterisations include
\[ \sigma^2(\vect{x}) = \exp\!\left(s(\vect{x})\right) \]
or
\[ \sigma^2(\vect{x}) = \operatorname{softplus}\!\left(s(\vect{x})\right)+\varepsilon, \]
with a small \(\varepsilon>0\) for numerical safety.
With the exponential parameterisation,
\[ s(\vect{x}) = \log \sigma^2(\vect{x}), \]
so the network directly predicts the log-variance.
With softplus, \(s(\vect{x})\) is simply an unconstrained score that is transformed into a positive variance.
The network can output any real number; the parameterisation ensures that the resulting variance is valid.
Let
\[ \mu_i=\mathrm{f}_1\!\left[\vect{x}_i,\params\right], \qquad s_i=\mathrm{f}_2\!\left[\vect{x}_i,\params\right], \qquad \sigma_i^2=\exp(s_i). \]
Then the Gaussian NLL becomes
\[ \boxed{ \loss[\params] = \sum_{i=1}^{I} \left[ \frac12\log(2\pi\sigma_i^2) + \frac{(y_i-\mu_i)^2}{2\sigma_i^2} \right] } \tag{5.15} \]
Both the mean and the variance now affect the loss for each example.
The heteroscedastic NLL contains two competing terms:
\[ \underbrace{ \frac{(y_i-\mu_i)^2}{2\sigma_i^2} }_{\text{residual penalty}} \qquad+ \qquad \underbrace{ \frac12\log\sigma_i^2 }_{\text{uncertainty penalty}} \]
Together, these terms learn input-dependent variance without allowing variance to grow without penalty.
Per-example Gaussian NLL as \(\sigma_i^2\) varies for a fixed residual.
Per-example Gaussian NLL as \(\sigma_i^2\) varies for a fixed residual.
| Homoscedastic | Heteroscedastic | |
|---|---|---|
| Mean | \(\mu_i=\model{\vect{x}_i}\) | \(\mu_i=\mathrm{f}_1\!\left[\vect{x}_i,\params\right]\) |
| Variance | one shared \(\sigma^2\) | \(\sigma_i^2\) varies with \(\vect{x}_i\) |
| Network predicts | mean only | mean and an unconstrained variance score \(s\) |
| Uncertainty | same everywhere | input-dependent |
| Loss | Gaussian NLL; reduces to least squares if \(\sigma^2\) fixed | Gaussian NLL with per-example variance |
Heteroscedastic regression parameterises both a conditional mean and an input-dependent variance.
Network outputs and predictive uncertainty for homoscedastic and heteroscedastic Gaussian regression.
Network outputs and predictive uncertainty for homoscedastic and heteroscedastic Gaussian regression.
\[ y\mid\vect{x}\sim\normal(\mu,\sigma^2). \]
\[ \boxed{ \text{choose a distribution} \rightarrow \text{predict its parameters} \rightarrow \text{NLL gives the loss} } \]
In binary classification, each input belongs to one of two classes:
\[ y\in\{0,1\}. \]
Here \(y\) is the class label.
Examples:
Following the recipe, we need a probability distribution defined on the discrete domain \(\{0,1\}\).
The Bernoulli distribution has one parameter
\[ \lambda\in[0,1], \]
where \(\lambda\) is the probability of class \(1\):
\[ p(y\mid\lambda) = \begin{cases} 1-\lambda, & y=0,\\[4pt] \lambda, & y=1. \end{cases} \tag{5.16} \]
Therefore
\[ p(y=1\mid\lambda)=\lambda, \qquad p(y=0\mid\lambda)=1-\lambda. \]
A Bernoulli distribution assigns probabilities \(1-\lambda\) and \(\lambda\) to its two outcomes.
Because \(y\) is either \(0\) or \(1\), equation 5.16 can be written compactly as
\[ \boxed{ p(y\mid\lambda) = (1-\lambda)^{1-y}\lambda^y } \tag{5.17} \]
| Observed label | What survives? | Likelihood |
|---|---|---|
| \(y=0\) | \(\lambda^0=1\) | \(1-\lambda\) |
| \(y=1\) | \((1-\lambda)^0=1\) | \(\lambda\) |
The exponents act as switches: the observed label selects the probability assigned to the class that actually occurred.
A Bernoulli probability is constrained to \(0<\lambda<1\). A raw linear output unit can produce any real value.
Start with odds:
\[ \text{odds} = \frac{\lambda}{1-\lambda}. \]
Then take the logarithm:
\[ \boxed{ z = \log\frac{\lambda}{1-\lambda} } \]
This \(z\in\reals\) is the logit.
| Probability \(\lambda\) | Odds | Logit \(z\) |
|---|---|---|
| \(0.25\) | \(1:3\) | \(-\log 3\) |
| \(0.50\) | \(1:1\) | \(0\) |
| \(0.75\) | \(3:1\) | \(\log 3\) |
The sigmoid is the inverse log-odds transformation: it converts an unconstrained logit back into a probability.
Let the network produce an unconstrained logit
\[ z=\model{\vect{x}}\in\reals. \]
Invert the log-odds transformation with the logistic sigmoid:
\[ \sigmoid(z) = \frac{1}{1+\exp(-z)}. \tag{5.18} \]
and define
\[ \boxed{ \lambda = \sigmoid\!\left(\model{\vect{x}}\right) } \]
Network logit, sigmoid transformation, and resulting Bernoulli probabilities across the input.
Substituting \(\lambda=\sigmoid(\model{\vect{x}})\) into equation 5.17 gives
\[ \boxed{ p(y\mid\vect{x}) = \left(1-\sigmoid(\model{\vect{x}})\right)^{1-y} \sigmoid(\model{\vect{x}})^y } \tag{5.19} \]
The predictive output is a Bernoulli distribution; a class label is obtained later by thresholding.
Define
\[ \lambda_i = \sigmoid\!\left(\model{\vect{x}_i}\right). \]
For one observation,
\[ -\log p(y_i\mid\vect{x}_i) = -\log\!\left[(1-\lambda_i)^{1-y_i}\lambda_i^{y_i}\right] \]
\[ = -(1-y_i)\log(1-\lambda_i) -y_i\log\lambda_i. \]
Summing over the dataset gives
\[ \boxed{ \loss[\params] = \sum_{i=1}^{I} \left[ -(1-y_i)\log(1-\lambda_i) -y_i\log\lambda_i \right] } \tag{5.20} \]
This is the binary cross-entropy (BCE) loss. We will explain the cross-entropy terminology later.
For a single example:
| True label | Per-example loss |
|---|---|
| \(y=1\) | \(-\log\lambda\) |
| \(y=0\) | \(-\log(1-\lambda)\) |
\[ \exloss_i = -\log p(y_i\mid\vect{x}_i). \]
For example:
| Probability assigned to the true class | NLL / BCE contribution |
|---|---|
| \(0.90\) | \(0.105\) |
| \(0.50\) | \(0.693\) |
| \(0.10\) | \(2.303\) |
| \(0.01\) | \(4.605\) |
Confidently assigning very little probability to the true class is penalised heavily.
Binary cross-entropy as a function of the predicted probability for \(y=0\) and \(y=1\).
For each training example, let
\[ \lambda_i = p(y=1\mid\vect{x}_i). \]
Then maximum likelihood encourages:
Equivalently, the network learns a real-valued score \(z_i=\model{\vect{x}_i}\) such that:
This is the probabilistic interpretation of the binary classifier: the logit is the quantity being learned, and the sigmoid is a fixed readout of it.
After training,
\[ \lambda = \sigmoid\!\left(\model[\hat{\params}]{\vect{x}}\right) = p(y=1\mid\vect{x}). \]
If we need a class label, use the maximum-probability decision:
\[ \hat y = \begin{cases} 1, & \lambda>0.5,\\[4pt] 0, & \lambda\le0.5. \end{cases} \]
Because sigmoid is monotonic and \(\sigmoid(0)=0.5\),
\[ \lambda>0.5 \quad\Longleftrightarrow\quad \model[\hat{\params}]{\vect{x}}>0. \]
\(0.5\) is the natural maximum-probability threshold here; a deployed system may choose a different threshold when the costs of false positives and false negatives differ.
Mathematically, we have described the pipeline as
\[ z \xrightarrow{\sigmoid} \lambda \xrightarrow{\text{BCE}} \exloss. \]
Numerically, explicitly computing \(\lambda\) extremely close to \(0\) or \(1\) and then taking \(\log\lambda\) or \(\log(1-\lambda)\) can be unstable.
Logits are unconstrained real scores; sigmoid outputs are probabilities.
\[ \lambda = p(y=1\mid\vect{x}) = \sigmoid\!\left(\model{\vect{x}}\right). \]
\[ \boxed{ \exloss = -(1-y)\log(1-\lambda)-y\log\lambda } \]
\[ \boxed{ \text{Bernoulli model} +\text{sigmoid parameterisation} \Longrightarrow \text{binary cross-entropy} } \]
The goal is to assign an input example \(\vect{x}\) to one of \(K>2\) classes:
\[ y\in\{1,2,\ldots,K\}. \]
Examples:
As before, we apply the same loss-construction recipe.
For labels taking one of \(K\) discrete values, use a categorical distribution.
Its parameters are
\[ \lambda_1,\lambda_2,\ldots,\lambda_K, \]
where
\[ \prob{y=k}=\lambda_k. \tag{5.21} \]
These parameters must satisfy:
Collect the class probabilities into one vector:
\[ \classprobs = \begin{bmatrix} \lambda_1\\ \lambda_2\\ \vdots\\ \lambda_K \end{bmatrix}. \]
Interpretation:
Use a network with \(K\) outputs:
\[ \vect{z}=\vmodel{\vect{x}}\in\reals^K. \]
Write the components as
\[ \vect{z}= \begin{bmatrix} z_1\\z_2\\\vdots\\z_K \end{bmatrix}. \]
These raw outputs are often called scores or logits.
Raw logits are not probabilities:
To convert logits into a valid categorical distribution, apply the softmax function.
For the \(k\)th class,
\[ \softmax_k[\vect{z}] = \frac{\exp(z_k)}{\sum_{k'=1}^{K}\exp(z_{k'})}. \tag{5.22} \]
Why this works:
Take three logits
\[ \vect{z}=(2,1,0). \]
Exponentiate each score:
\[ e^{\vect{z}} \approx (7.39,\;2.72,\;1.00), \qquad \sum_k e^{z_k}\approx11.11. \]
Then divide every positive score by the same total:
\[ \softmax(\vect{z}) \approx (0.665,\;0.245,\;0.090). \]
Softmax maps five logits to a categorical probability vector while preserving their ordering.
If the network produces logits
\[ \vect{z}=\vmodel{\vect{x}}, \]
then the class probabilities are
\[ \lambda_k = \softmax_k\!\left(\vmodel{\vect{x}}\right). \]
So the likelihood of label \(y=k\) is
\[ \prob{y=k\mid \vect{x}} = \softmax_k\!\left(\vmodel{\vect{x}}\right). \tag{5.23} \]
This is the multiclass analogue of the Bernoulli model used for binary classification.
Three logits and their softmax probabilities as the input varies; each probability vector sums to one.
For a training pair \((\vect{x}_i,y_i)\), the model assigns probability to the observed class \(y_i\).
The negative log-likelihood over the dataset is
\[ \loss[\params] = -\sum_{i=1}^{I} \log\left[ \softmax_{y_i} \left(\vmodel{\vect{x}_i}\right) \right]. \]
Substituting the softmax definition gives
\[ \loss[\params] = -\sum_{i=1}^{I} \left( f_{y_i}[\vect{x}_i,\params] - \log\left[\sum_{k'=1}^{K}\exp\big(f_{k'}[\vect{x}_i,\params]\big)\right] \right). \tag{5.24} \]
For one training example, equation 5.24 is
\[ \exloss_i = \underbrace{-f_{y_i}[\vect{x}_i,\params]}_{\text{reward a large true-class logit}} + \underbrace{\log\!\left[\sum_{k=1}^{K}\exp(f_k[\vect{x}_i,\params])\right]}_{\text{normalise against all competing logits}}. \]
Read it in three steps:
Multiclass cross-entropy is therefore a competition among logits, not an independent penalty on each score.
\[ \text{categorical model} + \text{softmax parameterisation} \Longrightarrow \text{multiclass NLL / cross-entropy loss}. \]
After training, the predictive distribution is
\[ \prob{y=k\mid \vect{x}} = \softmax_k\!\left(\vmodel[\hat{\params}]{\vect{x}}\right). \]
If we want a single class label, choose the most probable class:
\[ \hat y = \argmax_{k} \prob{y=k\mid \vect{x},\hat{\params}}. \]
This is the class with the largest softmax probability at that input.
Every class shares the same positive denominator. For any two classes \(j\) and \(k\),
\[ \softmax_j(\vect{z})>\softmax_k(\vect{z}) \iff \frac{e^{z_j}}{\sum_r e^{z_r}} > \frac{e^{z_k}}{\sum_r e^{z_r}} \iff z_j>z_k. \]
Therefore
\[ \boxed{ \argmax_{k}\softmax_k(\vect{z}) = \argmax_{k} z_k } \]
So for point classification:
This is analogous to the binary fact that thresholding the sigmoid probability at \(0.5\) is equivalent to thresholding the logit at \(0\).
Regression and classification are especially common, but the recipe is more general.
To predict any other kind of output:
General pattern:
\[ \text{target domain} \Longrightarrow \text{distribution choice} \Longrightarrow \text{negative log-likelihood loss}. \]
\[ \prob{y=k\mid\vect{x}} = \softmax_k\!\left(\vmodel{\vect{x}}\right). \]
\[ \boxed{ \text{categorical distribution} +\softmax \Longrightarrow \text{multiclass cross-entropy} } \]
Often, one model must make several predictions from the same input.
Instead of a scalar target \(y\), write
\[ \vect{y} = (y_1,y_2,\ldots,y_D). \]
Examples:
A full joint distribution can model dependencies between components of \(\vect{y}\).
A common simplification is to treat the output components as conditionally independent given the input.
Under the output-independence assumption,
\[ \prob{\vect{y}\mid \vmodel{\vect{x}}} = \prod_{d=1}^{D} \prob{y_d\mid \vect{f}_d\!\left[\vect{x},\params\right]}. \tag{5.25} \]
where:
This is a modelling assumption, not something guaranteed by using a neural network.
Suppose every target component is real-valued:
\[ y_d\in\reals. \]
A simple model uses one Gaussian for each output:
\[ y_d\mid\vect{x} \sim \normal(\mu_d,\sigma_d^2), \qquad \mu_d=\vect{f}_d\!\left[\vect{x},\params\right]. \]
Suppose each output component is a \(K\)-class label:
\[ y_d\in\{1,2,\ldots,K\}. \]
Use one categorical distribution for each \(y_d\).
For output component \(d\), the network must produce \(K\) logits:
\[ \vect{f}_d\!\left[\vect{x},\params\right] = \big(z_{d1},z_{d2},\ldots,z_{dK}\big). \]
Softmax converts those logits into the categorical probabilities for that component.
So a multi-output classifier may contain one group of logits per predicted label.
For training example \(i\), write \(y_{id}\) for output component \(d\).
\[ \loss[\params] = -\sum_{i=1}^{I} \sum_{d=1}^{D} \log \prob{y_{id}\mid \vect{f}_d\!\left[\vect{x}_i,\params\right]}. \tag{5.26} \]
Read the two sums from the inside out:
\[ \boxed{\text{total loss} = \text{sum over examples of the sum over outputs}} \]
The additive form comes directly from the conditional-independence factorisation.
The same product-to-sum rule appears again.
For one training example:
\[ \prob{\vect{y}\mid\vect{x}} = \prod_{d=1}^{D}\prob{y_d\mid\vect{x}}. \]
Taking negative logs gives
\[ -\log\prob{\vect{y}\mid\vect{x}} = -\sum_{d=1}^{D}\log\prob{y_d\mid\vect{x}}. \]
So independent output distributions imply additive per-output NLL terms.
The components of \(\vect{y}\) do not need to share the same domain or distribution.
Example: predict both wind direction and wind strength.
| Output | Domain | Possible distribution |
|---|---|---|
| direction | \((-\pi,\pi]\) | von Mises |
| strength | \(\reals_{+}\) | exponential |
Under conditional independence,
\[ \prob{\text{direction},\text{strength}\mid\vect{x}} = \prob{\text{direction}\mid\vect{x}} \prob{\text{strength}\mid\vect{x}}. \]
Their negative log-likelihood terms then add in the training loss.
The maximum-likelihood recipe extends well beyond Gaussian regression.
| Target/domain | Distribution | Typical use |
|---|---|---|
| \(y\in\reals\) | normal | ordinary univariate regression |
| \(y\in\reals\) | Laplace or \(t\) | robust regression |
| \(y\in\reals\) | mixture of Gaussians | multimodal regression |
| \(y\in\reals_{+}\) | exponential or gamma | positive magnitudes |
| Target/domain | Distribution | Typical use |
|---|---|---|
| \(y\in[0,1]\) | beta | proportions |
| \(\vect{y}\in\reals^K\) | multivariate normal | correlated multivariate regression |
| \(y\in(-\pi,\pi]\) | von Mises | circular direction |
The target domain constrains the candidate distributions; modelling assumptions decide which one to use.
| Target/domain | Distribution | Typical use |
|---|---|---|
| \(y\in\{0,1\}\) | Bernoulli | binary classification |
| \(y\in\{1,\ldots,K\}\) | categorical | multiclass classification |
| \(y\in\{0,1,2,\ldots\}\) | Poisson | event counts |
| \(\vect{y}\in\operatorname{Perm}(1,\ldots,K)\) | Plackett–Luce | rankings / permutations |
The general recipe remains unchanged:
\[ \text{domain} \Longrightarrow \text{distribution} \Longrightarrow \text{parameterisation} \Longrightarrow \text{NLL}. \]
The factorisation in equation 5.25 is convenient, but it discards dependencies between outputs.
For example:
If these dependencies matter, a product of independent univariate distributions may be inadequate.
Then we may need a joint multivariate or structured distribution that models relationships between outputs explicitly.
Independence is therefore a simplification of the statistical model, not a statement that the real outputs are unrelated.
For several continuous outputs, one alternative is a multivariate normal:
\[ \vect{y}\mid\vect{x} \sim \normal\!\left(\mean(\vect{x}),\mat{\Sigma}(\vect{x})\right). \]
Two bivariate Gaussian models: diagonal covariance gives an axis-aligned ellipse; non-zero covariance tilts it.
\[ \text{independent per-output distributions} \quad\text{vs}\quad \text{one joint distribution} \]
Use the simpler factorisation when adequate; use a joint model when dependencies are part of what must be predicted.
\[ \vect{y}=(y_1,\ldots,y_D). \]
\[ \prob{\vect{y}\mid\vect{x}} = \prod_{d=1}^{D}\prob{y_d\mid\vect{x}}. \]
\[ \boxed{ \loss[\params] = -\sum_i\sum_d \log\prob{y_{id}\mid \vect{f}_d\!\left[\vect{x}_i,\params\right]} } \]
We already have a training objective:
\[ \loss[\params] = -\sum_i \log p\!\left(y_i\mid \model{\vect{x}_i}\right). \]
The same fitting problem can be viewed in several ways:
| View | Question |
|---|---|
| Negative log-likelihood | How well did the model score the observations we actually saw? |
| Cross-entropy | How well would the model score outcomes generated by the data distribution? |
| KL divergence | How much extra log-loss comes from the model distribution not matching the data distribution? |
These are not three competing losses in this setting. They are closely related views of the same fitting problem.
For a discrete observed outcome \(y\), we already used
\[ \boxed{\text{surprise}(y)=-\log p(y)}. \]
| Probability assigned to the outcome | Surprise \(-\log p\) |
|---|---|
| \(0.9\) | \(0.105\) |
| \(0.5\) | \(0.693\) |
| \(0.1\) | \(2.303\) |
| \(0.01\) | \(4.605\) |
Suppose outcomes are generated by a distribution \(q\).
Before observing the next outcome, some distributions are much more predictable than others.
Entropy is the average surprise when outcomes are drawn from \(q\) and scored using \(q\) itself:
\[ \boxed{ H(q) = \expectsub{Y\sim q}{-\log q(Y)} } \]
Entropy is a property of the distribution, not of one particular observed value.
Two distributions over four outcomes. Concentrated probability gives lower entropy; more evenly spread probability gives higher entropy.
In security, people often speak loosely of a high-entropy key or password. More precisely, the entropy belongs to the source or distribution it was drawn from: many plausible outputs mean greater uncertainty before the value is known.
Now distinguish two distributions:
For the moment we suppress the input \(x\) to keep the notation simple. In supervised learning, these become conditional distributions such as \(q(y\mid x)\) and \(p(y\mid x)\).
There are now two ways to score outcomes drawn from \(q\):
\[ \begin{aligned} H(q) &= \expectsub{Y\sim q}{-\log q(Y)} &&\text{score }q\text{ using }q,\\[6pt] \xent{q}{p} &= \expectsub{Y\sim q}{-\log p(Y)} &&\text{score }q\text{ using }p. \end{aligned} \]
Entropy: how uncertain the data are intrinsically.
Cross-entropy: how surprised model \(p\) is, on average, by data drawn from \(q\).
Suppose the data distribution is \(q\), while the model predicts \(p\):
| Outcome \(y\) | \(q(y)\) | \(p(y)\) | Model surprise \(-\log p(y)\) | Weighted surprise \(q(y)[-\log p(y)]\) |
|---|---|---|---|---|
| 1 | \(0.50\) | \(0.60\) | \(0.511\) | \(0.255\) |
| 2 | \(0.30\) | \(0.30\) | \(1.204\) | \(0.361\) |
| 3 | \(0.20\) | \(0.10\) | \(2.303\) | \(0.461\) |
Add the weighted surprises:
\[ \xent{q}{p} \approx 0.255+0.361+0.461 = 1.077\ \text{nats}. \]
\[ \boxed{ \text{cross-entropy} = \text{average model surprise on data from }q } \]
Cross-entropy contains two conceptually different sources of log-loss:
\[ \boxed{ \xent{q}{p} = H(q) + \kl{q}{p} } \]
Cross-entropy decomposed into entropy plus KL divergence for the worked example.
\(H(q)\) — intrinsic uncertainty
Even a perfect model cannot make the underlying data-generating process more predictable than it is.
\(D_{\mathrm{KL}}(q\|p)\) — model mismatch
This is the extra expected log-loss caused by using \(p\) instead of \(q\).
\[ \boxed{ \kl{q}{p} = \text{cross-entropy} - \text{entropy} } \]
KL divergence is the part of the cross-entropy attributable to model mismatch.
When fitting the model, \(q\) is fixed. Changing the model changes \(p\), not the data-generating distribution.
Therefore \(H(q)\) is constant with respect to the model parameters:
\[ \xent{q}{p} = \underbrace{H(q)}_{\text{fixed}} + \underbrace{\kl{q}{p}}_{\text{changes with }p}. \]
Hence
\[ \boxed{ \argmin_p \xent{q}{p} = \argmin_p \kl{q}{p} } \]
We cannot reduce the intrinsic uncertainty in \(q\); fitting can only reduce the mismatch between \(p\) and \(q\).
For discrete outcomes,
\[ \boxed{ \kl{q}{p} = \sum_y q(y) \log\frac{q(y)}{p(y)} } \]
Read one term from right to left:
The formula formalises the idea we already have: average extra log-loss caused by using \(p\) instead of \(q\).
For continuous outcomes, probability masses become densities and the sum becomes an integral:
\[ \kl{q}{p} = \int q(y) \log\frac{q(y)}{p(y\mid\distparams)}\,dy. \tag{5.27} \]
For continuous variables, the corresponding entropy is differential entropy. We use the same cross-entropy/NLL connection here, but differential entropy does not share every property of discrete Shannon entropy.
KL divergence for the same two distributions in both argument orders.
The true data distribution \(q\) is unknown. We only observe training examples drawn from it.
Population cross-entropy is an expectation:
\[ \xent{q}{p} = \expectsub{Y\sim q}{-\log p(Y)}. \]
Estimate that expectation with the sample average:
\[ \xent{q}{p} \approx -\frac{1}{I} \sum_{i=1}^{I} \log p(y_i). \]
\[ \boxed{ \text{expected model surprise} \longrightarrow \text{average surprise on observed data} } \]
Observed samples and the model density evaluated at those samples.
That sample average is empirical cross-entropy; it is also the mean negative log-likelihood.
Return now to supervised learning, where the predictive distribution depends on the input. In population form, the corresponding cross-entropy averages \(-\log p(Y\mid X)\) over input-target pairs \((X,Y)\) drawn from the data distribution.
For the training set, the network supplies the distribution parameters for each observed input:
\[ \distparams_i = \model{\vect{x}_i}. \]
The empirical cross-entropy is therefore
\[ -\frac1I \sum_{i=1}^{I} \log p\!\left(y_i\mid\model{\vect{x}_i}\right). \]
Apart from the positive scale factor \(1/I\), this is exactly the NLL used throughout the lecture:
\[ \boxed{ \text{minimum empirical cross-entropy} \Longleftrightarrow \text{minimum NLL} \Longleftrightarrow \text{maximum likelihood} } \]
| Viewpoint | What is held conceptually in focus? | Quantity |
|---|---|---|
| Maximum likelihood / NLL | the observed training examples | log-loss on the observed targets |
| Cross-entropy | the data distribution and model distribution | expected model log-loss under the data distribution |
| KL divergence | mismatch between the two distributions | cross-entropy minus the entropy of the data distribution |
In this supervised maximum-likelihood setting, cross-entropy does not introduce a second loss to optimise. It explains the same objective as distribution matching.
Binary classification
\[ \exloss = -y\log\lambda-(1-y)\log(1-\lambda) \]
is both Bernoulli negative log-likelihood and binary cross-entropy.
Multiclass classification
\[ \exloss=-\log\lambda_y \]
is both categorical negative log-likelihood and multiclass cross-entropy.
The formula is the same; NLL and cross-entropy describe two ways of interpreting it.
We started with families of functions
\[ \model{\vect{x}}. \]
The loss function answers:
How do we decide which parameter setting is best?
Interpret the network as predicting parameters of a probability distribution:
\[ \distparams = \model{\vect{x}}, \qquad y\sim p(y\mid\distparams). \]
For a new prediction problem:
\[ \boxed{ \loss[\params] = -\sum_i \log p\!\left(y_i\mid \model{\vect{x}_i}\right) } \]
The distributional assumptions determine the concrete form of the loss.
| Prediction problem | Distribution | Parameterisation | Resulting loss |
|---|---|---|---|
| real-valued regression | normal | predicted mean | least squares |
| binary classification | Bernoulli | sigmoid probability | binary cross-entropy |
| multiclass classification | categorical | softmax probabilities | multiclass cross-entropy |
| multiple outputs | product of chosen distributions | one parameter set per output | sum of per-output NLLs |
Extensions include:
Likelihood view
\[ \text{choose parameters that make the observed data likely} \]
Cross-entropy view
\[ \text{minimise average model log-loss on the empirical data distribution} \]
Both give the same optimisation criterion:
\[ \boxed{ \text{maximum likelihood} \Longleftrightarrow \text{minimum NLL} \Longleftrightarrow \text{minimum empirical cross-entropy} } \]
A learning problem now has two pieces:
The remaining question is computational:
\[ \boxed{ \text{How do we find } \hat{\params} = \argmin_{\params} \loss[\params]? } \]
That is the subject of the next chapter: model training and optimisation.
Eoin O’Brien · eoin@eoin.ai