Sub topic 6
Fitting by maximum likelihood
This chapter assumes you know the sigmoid model from the previous chapters, where p = sigmoid(w·x + b) is the predicted probability of class 1. You should also be comfortable with basic probability (independent events multiply) and with logarithms. Here you will see where the training objective comes from. The next chapter turns the result into log loss.
The question maximum likelihood answers
The sigmoid model has parameters w and b, and every choice of them gives different predicted probabilities. Maximum likelihood estimation (MLE) picks the parameters under which the training labels you actually observed would have been most probable.
Linear regression has a natural error to minimize: the squared distance between prediction and target. Logistic regression predicts probabilities but observes only 0/1 labels, so there is no obvious distance to measure. Likelihood gives a principled one.
Probability of one label
For one example with features x and label y (0 or 1), the model gives p = P(y=1 | x). The probability the model assigns to the observed label is:
pify = 11 - pify = 0
These two cases fit in one expression, the Bernoulli probability:
P(y | x) = p^y * (1 - p)^(1 - y)When y = 1, the second factor is (1 - p)^0 = 1, so only p remains. When y = 0, the first factor is p^0 = 1, so only 1 - p remains.
From one example to a dataset
Assume the examples are independent given their features. The probability of the whole label vector is then the product over examples. Viewed as a function of the parameters, with the data held fixed, it is called the likelihood:
L(w, b) = Π_i p_i^(y_i) * (1 - p_i)^(1 - y_i)Here p_i = sigmoid(w·x_i + b). MLE chooses the w and b that make L as large as possible.
Why we take the log
Products of many numbers below 1 are hard to work with, for two reasons:
- Underflow. Floating-point numbers cannot represent very small values. A product of probabilities shrinks toward zero and eventually becomes exactly
0.0. - Awkward derivatives. The derivative of a long product needs the product rule repeatedly. A sum is easy to differentiate term by term.
The logarithm is strictly increasing, so the parameters that maximize L also maximize log L. The log turns the product into a sum:
log L(w, b) = Σ_i [ y_i * log(p_i) + (1 - y_i) * log(1 - p_i) ]This is the log-likelihood. Each term is at most 0, because it is the log of a probability. A value closer to zero means the model found the labels less surprising.
import numpy as np
print(0.5 ** 1000) # about 9.3e-302, still representable
print(0.5 ** 1100) # 0.0, underflow
print(1100 * np.log(0.5)) # about -762.5, no problem as a sum of logsComputing the log-likelihood
The code below evaluates the log-likelihood of a tiny one-feature dataset for three candidate parameter settings.
import numpy as np
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
X = np.array([[-2.0], [-1.0], [0.5], [1.0], [2.0]])
y = np.array([0, 0, 1, 0, 1])
def log_likelihood(w, b):
p = sigmoid(X @ w + b)
return np.sum(y * np.log(p) + (1 - y) * np.log(1 - p))
for w, b in [(0.0, 0.0), (1.0, 0.0), (-1.0, 0.0)]:
print(w, b, log_likelihood(np.array([w]), b))The values are about -3.47, -2.35, and -6.85. The first setting predicts 0.5 everywhere, so each of the five terms is log(0.5). The second has a positive slope, which agrees with the general trend that larger x goes with label 1, so it scores higher. The third has a negative slope and confidently predicts the wrong way, so it scores much lower. Training is a search for the parameters with the highest value.
From maximizing to minimizing
Optimization libraries and textbooks usually minimize. Negate the log-likelihood and divide by n to get the negative mean log-likelihood:
J(w, b) = -(1/n) * Σ_i [ y_i * log(p_i) + (1 - y_i) * log(1 - p_i) ]Dividing by n does not change which parameters are best. It keeps the loss on a comparable scale as the dataset grows, which makes learning rates easier to choose. This J is the log loss, also called binary cross-entropy, and the next chapter studies it in detail.
No closed-form solution
Linear regression with squared error has a closed-form answer, the normal equations. Setting the gradient of the log-likelihood to zero for logistic regression gives equations that mix w and b inside the sigmoid. They cannot be solved algebraically, so you fit the model with an iterative method such as gradient descent or a Newton-type solver. The log loss is convex in w and b, so these methods do not get stuck in local minima.
Common errors and limits
- Confusing likelihood with probability of the parameters. The likelihood is the probability of the data as a function of the parameters. It does not say how probable the parameters are, and it does not sum to 1 over parameter values.
- Violating independence. The product form assumes independent examples. Repeated measurements of the same patient, or time series with strong autocorrelation, break this. The fit still runs, but standard errors and some conclusions become unreliable. Split by group when you evaluate.
- Taking the log of 0. If
preaches exactly 0 or 1 in floating point,np.logreturns-infand the loss becomesinfornan. Libraries clip probabilities to a small range, such as1e-15, before taking logs. - Perfect separation. If a line separates the classes with no errors, the likelihood keeps increasing as the weights grow. The supremum is never reached, so unregularized MLE has no finite solution. Regularization, covered later, fixes this.
- MLE can overfit. It finds the parameters that best explain the training labels, including noise. With many features and few examples, the fit can be too confident.
Summary of the chain
Each step in this chapter is a deliberate choice: Bernoulli labels, independence, log, negation, and averaging. Together they turn "make the observed labels likely" into the loss function you minimize in the next chapters.
Exercise
A model assigns probabilities p = 0.9, 0.2, and 0.6 to three examples with labels y = 1, 0, 1. Compute the log-likelihood (natural log) and the negative mean log-likelihood. Which example contributes most to the loss?
Show answer
The per-example terms are log(0.9) ≈ -0.105 for the first example (y=1, so use p), log(1 - 0.2) = log(0.8) ≈ -0.223 for the second (y=0, so use 1 - p), and log(0.6) ≈ -0.511 for the third. The log-likelihood is about -0.105 - 0.223 - 0.511 = -0.839. The negative mean log-likelihood is 0.839 / 3 ≈ 0.280. The third example contributes most, because the model gave only 0.6 to the correct label.
Exercise
Why can the likelihood of 1,000 independent examples be computed incorrectly as exactly 0.0 even when every individual probability is positive, and what is the standard fix?
Show answer
The product of many numbers below 1 can be smaller than the smallest positive floating-point number, so it underflows to 0.0. The fix is to work with the sum of log probabilities (the log-likelihood), which stays in a normal numeric range.