Unit 5, lesson 28

Maximum Likelihood and Cross-Entropy

How the Bernoulli likelihood of observed labels leads through the log likelihood to binary cross-entropy, how maximum likelihood estimation fits a model, and how a prior distribution gives MAP estimation and penalties.

  • Video 28
  • Logistic Regression and Likelihood

Logistic regression is trained by minimizing an average of negative logarithms, and it is fair to ask why that loss was chosen rather than the number of wrong labels or the squared error. The answer starts from a probability model for the labels. This lesson writes the likelihood of the observed labels, turns its product into a sum and then into the binary cross-entropy, finds a maximum likelihood estimate in closed form for a simple model, and shows how a prior distribution on the weights produces the ridge and lasso penalties.

Key terms

Likelihood

Definition Fix observed training data (x1,y1),…,(xn,yn)(\mathbf{x}_1, y_1), \dots, (\mathbf{x}_n, y_n) and a model that gives, for each parameter value θ\boldsymbol{\theta} in an allowed set Θ\Theta, the probability Pθ(y∣x)P_{\boldsymbol{\theta}}(y \mid \mathbf{x}) that the label equals yy when the features are x\mathbf{x}. The likelihood is the probability that the model gives to the observed labels, viewed as a function of θ\boldsymbol{\theta} in Θ\Theta with the data held fixed. If the labels are modeled as conditionally independent given their features and θ\boldsymbol{\theta}, it is the product

L(θ)=∏i=1nPθ(yi∣xi).\mathcal{L}(\boldsymbol{\theta}) = \prod_{i=1}^{n} P_{\boldsymbol{\theta}}(y_i \mid \mathbf{x}_i) .

Without the independence assumption the joint probability of the labels need not factor this way. For a continuous target the probabilities are replaced by densities.

In plain words A probability fixes the parameters and asks which labels might occur. Likelihood runs the other way. It fixes the labels that did occur and asks how probable they were under each parameter value. Its values are not probabilities of parameter values and need not add or integrate to 11 over Θ\Theta. Turning them into probabilities about θ\boldsymbol{\theta} requires a prior distribution and Bayes’ rule.

Example Suppose the labels 1,0,11, 0, 1 are modeled as independent, each equal to 11 with the same probability pp, where 0≤p≤10 \le p \le 1. Then L(p)=p(1−p)p=p2(1−p)\mathcal{L}(p) = p(1 - p)p = p^2(1 - p), with L(0.5)=0.125\mathcal{L}(0.5) = 0.125, L(2/3)=4/27≈0.1481\mathcal{L}(2/3) = 4/27 \approx 0.1481 and L(0.9)=0.081\mathcal{L}(0.9) = 0.081. The area under L\mathcal{L} for 0≤p≤10 \le p \le 1 is 1/3−1/4=1/121/3 - 1/4 = 1/12, so the likelihood curve is not a probability density for pp.

Bernoulli likelihood

Definition A label YY in {0,1}\{0, 1\} has a Bernoulli distribution with parameter pp, where 0≤p≤10 \le p \le 1, when P(Y=1)=pP(Y = 1) = p and P(Y=0)=1−pP(Y = 0) = 1 - p. Both cases fit in one formula,

P(Y=y)=py(1−p)1−y,P(Y = y) = p^{y}(1 - p)^{1 - y} ,

for yy in {0,1}\{0, 1\}, with 000^0 read as 11. If a classifier gives example ii the probability pi=Pθ(1∣xi)p_i = P_{\boldsymbol{\theta}}(1 \mid \mathbf{x}_i) of class 11, and the labels are conditionally independent given their features and θ\boldsymbol{\theta}, the Bernoulli likelihood is

L(θ)=∏i=1npi yi(1−pi)1−yi.\mathcal{L}(\boldsymbol{\theta}) = \prod_{i=1}^{n} p_i^{\,y_i}(1 - p_i)^{1 - y_i} .

For logistic regression θ=(b,w)\boldsymbol{\theta} = (b, \mathbf{w}) and pi=σ(b+w⊤xi)p_i = \sigma(b + \mathbf{w}^{\top}\mathbf{x}_i).

In plain words The exponents pick the right factor. An example with yi=1y_i = 1 contributes pip_i and an example with yi=0y_i = 0 contributes 1−pi1 - p_i, and in both cases that is the probability the model gave to the label that actually occurred. One example whose actual label received a probability near 00 pulls the whole product toward 00.

Example The labels are 1,0,11, 0, 1. Candidate A predicts class-one probabilities 0.8,0.2,0.80.8, 0.2, 0.8, so every observed label receives probability 0.80.8 and the likelihood is 0.83=0.5120.8^3 = 0.512. Candidate B predicts 0.2,0.8,0.20.2, 0.8, 0.2, so every observed label receives 0.20.2 and the likelihood is 0.23=0.0080.2^3 = 0.008. The observed labels are 6464 times as probable under A as under B. This ranks two candidates and does not show that A is the best possible one.

Maximum likelihood estimation

Definition A maximum likelihood estimate (MLE) is a parameter value θ^\hat{\boldsymbol{\theta}} in Θ\Theta with L(θ^)≥L(θ)\mathcal{L}(\hat{\boldsymbol{\theta}}) \ge \mathcal{L}(\boldsymbol{\theta}) for every θ\boldsymbol{\theta} in Θ\Theta. An MLE need not exist, and when one exists it need not be unique. Take nn labels with kk ones, modeled as independent Bernoulli labels with one shared parameter pp in [0,1][0, 1]. For 0<p<10 < p < 1 the logarithm of the likelihood is ℓ(p)=kln⁡p+(n−k)ln⁡(1−p)\ell(p) = k \ln p + (n - k)\ln(1 - p), and setting its derivative to zero gives

ℓ′(p)=kp−n−k1−p=0.\ell'(p) = \frac{k}{p} - \frac{n - k}{1 - p} = 0 .

Multiplying by p(1−p)>0p(1 - p) > 0 gives k(1−p)=(n−k)pk(1 - p) = (n - k)p, so k=npk = np and p^=k/n\hat{p} = k/n. When 0<k<n0 < k < n the function ℓ\ell is strictly concave on 0<p<10 < p < 1, so the sample proportion is the unique MLE. When k=nk = n the likelihood pnp^n is largest at the endpoint p^=1\hat{p} = 1, and when k=0k = 0 at p^=0\hat{p} = 0. For logistic regression the MLE of (b,w)(b, \mathbf{w}) has no closed form and is computed numerically, and it does not exist as a finite vector when a hyperplane separates the two training classes.

In plain words Maximum likelihood picks the allowed parameter value under which the observed labels were most probable. With shared parameters, as in logistic regression, raising the probability of one example’s label often lowers another’s, and the MLE balances these pulls. A high training likelihood is a fitting criterion, not a guarantee. A model flexible enough to give every training label a probability near 11 can fit the training data almost perfectly and still predict new cases badly.

Example For the labels 1,0,11, 0, 1 we have k=2k = 2 and n=3n = 3, so the MLE of the shared probability is p^=2/3\hat{p} = 2/3, with likelihood 4/27≈0.14814/27 \approx 0.1481. That is larger than the values 0.1250.125 at p=0.5p = 0.5 and 0.0810.081 at p=0.9p = 0.9 found above. The estimate is the sample proportion, derived here from the shared independent Bernoulli model, and in a finite sample it need not equal the true probability.

Log likelihood and negative log likelihood

Definition The log likelihood is ℓ(θ)=ln⁡L(θ)\ell(\boldsymbol{\theta}) = \ln \mathcal{L}(\boldsymbol{\theta}), defined where L(θ)>0\mathcal{L}(\boldsymbol{\theta}) > 0. With conditionally independent labels it is a sum,

ℓ(θ)=∑i=1nln⁡Pθ(yi∣xi),\ell(\boldsymbol{\theta}) = \sum_{i=1}^{n} \ln P_{\boldsymbol{\theta}}(y_i \mid \mathbf{x}_i) ,

and for the Bernoulli model the term of example ii is yiln⁡pi+(1−yi)ln⁡(1−pi)y_i \ln p_i + (1 - y_i)\ln(1 - p_i). The negative log likelihood (NLL) is −ℓ(θ)-\ell(\boldsymbol{\theta}). The natural logarithm is strictly increasing, so maximizing L\mathcal{L}, maximizing ℓ\ell and minimizing −ℓ-\ell give the same parameter values. Dividing −ℓ-\ell by the positive number nn changes its values but not its minimizers.

In plain words The logarithm turns a product into a sum without changing which parameters are best. Each term ln⁡Pθ(yi∣xi)\ln P_{\boldsymbol{\theta}}(y_i \mid \mathbf{x}_i) is at most 00, so each NLL term is a nonnegative penalty, small when the observed label got a high probability and large when it got a probability near 00. A sum of moderate numbers is also far safer in floating point than a product of many numbers below 11.

Example For candidates A and B above, ln⁡0.512≈−0.6694\ln 0.512 \approx -0.6694 and ln⁡0.008≈−4.8283\ln 0.008 \approx -4.8283, so the NLL values are 0.66940.6694 and 4.82834.8283. Their difference is ln⁡64≈4.1589\ln 64 \approx 4.1589, the logarithm of the likelihood ratio. A model that gives each of 20002000 labels probability 0.50.5 has likelihood 2−20002^{-2000}, far below the smallest positive double-precision number, about 4.9×10−3244.9 \times 10^{-324}, so the computed product is exactly 00. Its log likelihood is −2000ln⁡2≈−1386.29-2000 \ln 2 \approx -1386.29, an ordinary number.

Binary cross-entropy

Definition For a label yy in {0,1}\{0, 1\} and a predicted probability pp of class 11 with 0<p<10 < p < 1, the log loss is

L(y,p)=−yln⁡p−(1−y)ln⁡(1−p),\begin{aligned} L(y, p) &= -y \ln p \\[0.4em] &- (1 - y)\ln(1 - p) , \end{aligned}

which equals −ln⁡p-\ln p when y=1y = 1 and −ln⁡(1−p)-\ln(1 - p) when y=0y = 0. For labels yiy_i and predicted probabilities pip_i, the binary cross-entropy, or mean log loss, is the Bernoulli NLL divided by nn,

R^(θ)=1n∑i=1nL(yi,pi).\hat{R}(\boldsymbol{\theta}) = \frac{1}{n}\sum_{i=1}^{n} L(y_i, p_i) .

The name comes from the cross-entropy H(q,p)=−qln⁡p−(1−q)ln⁡(1−p)H(q, p) = -q \ln p - (1 - q)\ln(1 - p) between two distributions on {0,1}\{0, 1\} with probabilities qq and pp of class 11. Each loss L(yi,pi)L(y_i, p_i) equals H(yi,pi)H(y_i, p_i), with the label acting as the distribution that puts all its probability on the observed class. For a logistic model with score zz and p=σ(z)p = \sigma(z), the loss of one example can be written from the score as L(y,σ(z))=ln⁡(1+ez)−yzL\bigl(y, \sigma(z)\bigr) = \ln(1 + e^{z}) - yz, its derivative with respect to the score is σ(z)−y=p−y\sigma(z) - y = p - y, and the first term can be computed as

ln⁡(1+ez)=max⁡(0,z)+ln⁡(1+e−∣z∣).\begin{aligned} \ln(1 + e^{z}) &= \max(0, z) \\[0.4em] &+ \ln\bigl(1 + e^{-\lvert z \rvert}\bigr) . \end{aligned}

In plain words Each example pays minus the log of the probability its actual label received, so a confident mistake is expensive and the cost grows without bound as that probability goes to 00. On average the loss favors the true probability. If a case is positive with probability qq, where 0<q<10 < q < 1, the expected loss H(q,p)H(q, p) has derivative (p−q)/(p(1−p))(p - q)/\bigl(p(1 - p)\bigr) in pp, so it falls until p=qp = q and rises after. A fitted model can still be miscalibrated because of finite data or a wrong model form. In code the right side of the last display is the safe way to compute ln⁡(1+ez)\ln(1 + e^{z}), since its exponent −∣z∣-\lvert z \rvert is never positive, and working from the score avoids taking the logarithm of a rounded probability. At z=40z = 40 with y=0y = 0, the computed σ(40)\sigma(40) rounds to exactly 11 in double precision and ln⁡(1−p)\ln(1 - p) fails, while the score form gives the correct loss of about 4040.

Example Candidate A has mean loss −ln⁡0.8≈0.2231-\ln 0.8 \approx 0.2231 and candidate B has −ln⁡0.2≈1.6094-\ln 0.2 \approx 1.6094. A single positive example given probability 0.010.01 costs −ln⁡0.01≈4.6052-\ln 0.01 \approx 4.6052, and given 0.990.99 it costs about 0.01010.0101. For one gradient step, take features 0,1,20, 1, 2 with labels 0,0,10, 0, 1 and a logistic model started at b=w=0b = w = 0. Every probability is 1/21/2, so the values pi−yip_i - y_i are 1/2,1/2,−1/21/2, 1/2, -1/2. Their mean 1/61/6 is the derivative for bb, and the mean of (pi−yi)xi(p_i - y_i)x_i, which is (0+1/2−1)/3=−1/6(0 + 1/2 - 1)/3 = -1/6, is the derivative for ww. A step of size 0.60.6 gives b=−0.1b = -0.1 and w=0.1w = 0.1, the probabilities become about 0.47500.4750, 0.50.5 and 0.52500.5250, and the mean loss falls from ln⁡2≈0.6931\ln 2 \approx 0.6931 to about 0.66060.6606. One step moves the fit in the right direction on these training examples and does not finish the fitting.

Maximum a posteriori estimation

Definition A prior distribution is a probability distribution π(θ)\pi(\boldsymbol{\theta}) on the parameters, chosen before the data at hand are used, that describes which values are considered plausible. By Bayes’ rule the posterior satisfies π(θ∣data)∝L(θ) π(θ)\pi(\boldsymbol{\theta} \mid \text{data}) \propto \mathcal{L}(\boldsymbol{\theta})\,\pi(\boldsymbol{\theta}). A maximum a posteriori (MAP) estimate is a mode of the posterior, a value of θ\boldsymbol{\theta} that maximizes L(θ) π(θ)\mathcal{L}(\boldsymbol{\theta})\,\pi(\boldsymbol{\theta}), or equivalently minimizes −ln⁡L(θ)−ln⁡π(θ)-\ln \mathcal{L}(\boldsymbol{\theta}) - \ln \pi(\boldsymbol{\theta}).

Suppose the weights w1,…,wpw_1, \dots, w_p get independent priors and the intercept is left out of the prior. Dividing the MAP objective by nn gives the mean NLL R^(θ)\hat{R}(\boldsymbol{\theta}) plus a penalty, up to a constant that does not depend on θ\boldsymbol{\theta}. A normal, or Gaussian, prior with mean 00 and variance s2>0s^2 > 0 has −ln⁡π(wj)=wj2/(2s2)-\ln \pi(w_j) = w_j^2/(2s^2) plus a constant, so the MAP estimate minimizes

R^(θ)+λ2∥w∥22,λ=1ns2,\begin{gathered} \hat{R}(\boldsymbol{\theta}) + \frac{\lambda}{2}\lVert \mathbf{w} \rVert_2^2 , \\[0.4em] \lambda = \frac{1}{n s^2} , \end{gathered}

which is the ridge penalty. A Laplace prior with density e−∣wj∣/a/(2a)e^{-\lvert w_j \rvert / a}/(2a) and scale a>0a > 0 has −ln⁡π(wj)=∣wj∣/a-\ln \pi(w_j) = \lvert w_j \rvert / a plus a constant, which gives the lasso objective R^(θ)+λ∥w∥1\hat{R}(\boldsymbol{\theta}) + \lambda \lVert \mathbf{w} \rVert_1 with λ=1/(na)\lambda = 1/(na). Leaving the intercept unpenalized corresponds to a flat prior on bb, which is not a probability distribution on the whole real line. The penalized fit is still well defined when its objective has a minimizer, but calling it a posterior mode then needs a separate check that the posterior is a proper distribution.

In plain words The prior says which weights seemed plausible before these data, and MAP picks the parameter value with the highest posterior density. A normal prior centered at 00 pulls weights smoothly toward 00, which is ridge, and a Laplace prior has a sharp peak at 00, which is why lasso can set weights exactly to 00. With λ>0\lambda > 0 the MAP estimate is generally not the MLE. It is a single point and says nothing by itself about how uncertain the parameters are, which needs the whole posterior. A prior also depends on units, since a prior variance for a weight per kilometer means something else for a weight per meter. With the prior fixed, λ\lambda shrinks as nn grows, so the data count for more.

Example Take n=4n = 4 training examples and normal priors with mean 00 and variance s2=2s^2 = 2 on the weights, so λ=1/(4⋅2)=1/8\lambda = 1/(4 \cdot 2) = 1/8. A weight w=2w = 2 adds w2/(2s2)=4/4=1w^2/(2s^2) = 4/4 = 1 to the summed negative log prior, or 1/41/4 after dividing by nn. The ridge term gives the same value, (λ/2)w2=(1/16)⋅4=1/4(\lambda/2)w^2 = (1/16) \cdot 4 = 1/4. With Laplace priors of scale a=0.5a = 0.5 instead, λ=1/(4⋅0.5)=1/2\lambda = 1/(4 \cdot 0.5) = 1/2, and the same weight adds ∣w∣/a=4\lvert w \rvert / a = 4 to the sum, or 11 after dividing by nn, which matches λ∣w∣=1\lambda \lvert w \rvert = 1.

Check yourself

  1. A model gives probability 0.040.04 to class 11 for an example whose label is 11. Find the log loss of this example and compare it with the loss when the probability is 0.960.96. Then explain why maximizing the likelihood is the same as minimizing this kind of loss.
Show the answer

The observed label received probability 0.040.04, so the loss is −ln⁡0.04=ln⁡25≈3.2189-\ln 0.04 = \ln 25 \approx 3.2189. With probability 0.960.96 the loss is −ln⁡0.96≈0.0408-\ln 0.96 \approx 0.0408, about 7979 times smaller. The natural logarithm is strictly increasing, so a parameter value with a larger likelihood has a larger log likelihood. The minus sign reverses that order, so the best parameters minimize the NLL, and dividing by the positive nn keeps the same minimizers. Each example’s share of the NLL is minus the log of the probability given to its actual label, which is exactly the loss computed here.

  1. Five labels 1,1,0,1,01, 1, 0, 1, 0 are modeled as independent Bernoulli labels with one shared probability pp. Find the MLE of pp and the mean log loss at that value. Then suppose all five labels are 11. What is the MLE over 0≤p≤10 \le p \le 1, and what happens when an intercept-only logistic model p=σ(b)p = \sigma(b) is fitted to these labels?
Show the answer

There are k=3k = 3 ones among n=5n = 5 labels, so p^=3/5=0.6\hat{p} = 3/5 = 0.6. The mean log loss at this value is −(3ln⁡0.6+2ln⁡0.4)/5≈0.6730-(3 \ln 0.6 + 2 \ln 0.4)/5 \approx 0.6730, smaller than ln⁡2≈0.6931\ln 2 \approx 0.6931 at p=0.5p = 0.5, as it must be. With five ones the likelihood is p5p^5, which increases on [0,1][0, 1], so the MLE is the endpoint p^=1\hat{p} = 1. The logistic model reaches only σ(b)<1\sigma(b) < 1 for finite bb, and its mean loss ln⁡(1+e−b)\ln(1 + e^{-b}) keeps decreasing as bb grows, about 0.12690.1269 at b=2b = 2 and 0.00670.0067 at b=5b = 5, without reaching 00. No finite bb is an MLE, and gradient descent keeps increasing bb. A penalty or prior on bb would give a finite estimate, but it changes the objective.

  1. A logistic model with two weights is trained on n=10n = 10 examples by minimizing the mean NLL plus (λ/2)∥w∥22(\lambda/2)\lVert \mathbf{w} \rVert_2^2, with the intercept unpenalized. Which λ\lambda matches independent normal priors with mean 00 and variance 0.50.5 on the weights? Check your answer at w=(1,0)\mathbf{w} = (1, 0), and find λ\lambda for the same prior with n=20n = 20. A colleague calls the fitted weights maximum likelihood estimates and quotes the prior standard deviation as their uncertainty. What is wrong?
Show the answer

The match is λ=1/(ns2)=1/(10⋅0.5)=0.2\lambda = 1/(n s^2) = 1/(10 \cdot 0.5) = 0.2. At w=(1,0)\mathbf{w} = (1, 0) the summed negative log prior, without its constant, is (12+02)/(2⋅0.5)=1(1^2 + 0^2)/(2 \cdot 0.5) = 1, which is 0.10.1 after dividing by nn. The ridge term gives (0.2/2)(12+02)=0.1(0.2/2)(1^2 + 0^2) = 0.1 as well. With n=20n = 20 and the same prior, λ=1/(20⋅0.5)=0.1\lambda = 1/(20 \cdot 0.5) = 0.1. The fitted weights are a MAP estimate, which minimizes a penalized objective and is generally not the MLE. The prior standard deviation 0.5≈0.707\sqrt{0.5} \approx 0.707 describes plausibility before the data, not uncertainty after them, and a MAP point by itself gives no measure of posterior uncertainty.

How this lesson connects

It also uses rules of logarithms.