Introduction to Machine Learning

Maximum Likelihood
and Generalized Linear Models

One recipe behind every model we have built

Three questions, three kinds of answer

How much? A price: any real number.

The twenty Ames houses from linear regression

Will it happen? Yes or no.

O-ring damage on the 23 shuttle flights before Challenger

How many? A count.

Earthquakes of each magnitude on Earth, 2015 to 2024

Least squares answered the first, and logistic regression the second, with the same update rule. Today that stops being a coincidence: one recipe answers all three, and the only thing that changes between them is one function.

Six questions for today

  1. 1The likelihoodWhat does it mean for a model to explain the data?
  2. 2Yes or noWhat is the likelihood of an event that either happens or does not?
  3. 3One familyWhy do linear and logistic regression share one update rule?
  4. 4CountsWhat if the answer counts something?
  5. 5The recipeWhat do all three models share, and what are the parts called?
  6. 6In codeWhat does one GLM look like in ten lines of Python?

Every figure today is real data you can download: the Ames houses, the Challenger O-rings, and the US Geological Survey earthquake catalogue.

Probabilistic Interpretation of Linear Regression

Assume the noise is normally distributed around the model:

Noise model \( y^{(i)} = \theta^\top x^{(i)} + \varepsilon^{(i)}, \qquad \varepsilon^{(i)} \sim \mathcal{N}(0, \sigma^2) \)
slackline walker

the model is the line;
every step wobbles around it

\( p(\varepsilon^{(i)}) = \frac{1}{\sqrt{2\pi}\sigma} \exp\!\left( -\frac{(\varepsilon^{(i)})^2}{2\sigma^2} \right) \)
\( p(y^{(i)} \mid x^{(i)}; \theta) = \frac{1}{\sqrt{2\pi}\sigma} \exp\!\left( -\frac{(y^{(i)} - \theta^\top x^{(i)})^2}{2\sigma^2} \right) \)

Likelihood of Output Given Input

The examples are independent and identically distributed, so the dataset probability is a product:

\( \displaystyle L(\theta) = \prod_{i=1}^{m} p(y^{(i)} \mid x^{(i)}; \theta) = \prod_{i=1}^{m} \frac{1}{\sqrt{2\pi}\sigma} \exp\!\left( -\frac{(y^{(i)} - \theta^\top x^{(i)})^2}{2\sigma^2} \right) \)

Take the log, and the product becomes a sum:

\( \displaystyle \ell(\theta) = \log L(\theta) = m \log \frac{1}{\sqrt{2\pi}\sigma} - \frac{1}{\sigma^2} \cdot \frac{1}{2}\sum_{i=1}^{m} \left( y^{(i)} - \theta^\top x^{(i)} \right)^2 \)

Likelihood, feltThe twenty houses from linear regression, with the noise model laid over them

Each house glows by how probable the model finds its price. The intercept follows the slope, so the line always passes through the average house.

Maximize Log-Likelihood

The punchline Maximizing \( \ell(\theta) \) is minimizing \( \tfrac12 \sum_i (y^{(i)} - \theta^\top x^{(i)})^2 \)

Least squares was never an arbitrary choice. It is maximum likelihood under Gaussian noise.

The question that opens today What if the noise is not Gaussian?

Part 2 of 6

Yes or no

What is the likelihood of an event that either happens or does not?

The night before Challenger27 January 1986: will the cold hurt the seals?

The joints of the shuttle's boosters are sealed by rubber O-rings, six per flight. On 7 of the 23 flights before Challenger, some came back scorched or eroded.

The forecast for launch morning was 31°F, −0.6°C: more than 12°C colder than any flight before.

The Rogers Commission report later set two charts side by side: the flights with damage alone, where temperature seems not to matter, and all the flights. Press the second button.

A zero is data Every flight with no damage flew warm. The likelihood counts the flights that went fine as well as the ones that did not.

Data: Dalal, Fowlkes and Hoadley, Risk analysis of the space shuttle: pre-Challenger prediction of failure, JASA 84 (1989), via the UCI repository. Damage means at least one of the six O-rings came back eroded or scorched; on two flights, two of the six did. Flights launched at the same temperature are drawn side by side.

Why Not Least Squares in Logistic Regression?

\( h_\theta(x) = \dfrac{1}{1 + e^{-\theta^\top x}} = \sigma(\theta^\top x) \)
The output is a probability The label is 0 or 1, never in between. Squared error treats a probability like a measurement, and its noise is not Gaussian.
\( P(y = 1 \mid x; \theta) = h_\theta(x), \qquad P(y = 0 \mid x; \theta) = 1 - h_\theta(x) \)
\( p(y \mid x; \theta) = \big(h_\theta(x)\big)^{y} \big(1 - h_\theta(x)\big)^{1-y} \)   Bernoulli noise

The Bernoulli Distribution

If \(X\) is a random variable with a Bernoulli distribution, then:

\( \Pr(X = 1) = p = 1 - \Pr(X = 0) = 1 - q \)

Its probability mass function \(f\), over possible outcomes \(k\), is

\( f(k; p) = \begin{cases} p & k = 1 \\ q = 1 - p & k = 0 \end{cases} \)
\( f(k; p) = p^k (1-p)^{1-k} \quad \text{for } k \in \{0, 1\} \)

The Bernoulli distribution is the binomial distribution with \(n = 1\).

Define the Log-Likelihood

\( p(y \mid x; \theta) = \big(h_\theta(x)\big)^{y}\big(1 - h_\theta(x)\big)^{1-y} \quad \text{for all } (x, y) \)
\( \displaystyle L(\theta) = \prod_{i=1}^{m} \big(h_\theta(x^{(i)})\big)^{y^{(i)}} \big(1 - h_\theta(x^{(i)})\big)^{1 - y^{(i)}} \)
\( \displaystyle \ell(\theta) = \sum_{i=1}^{m} \left[ y^{(i)} \log h_\theta(x^{(i)}) + (1 - y^{(i)}) \log\big(1 - h_\theta(x^{(i)})\big) \right] \)

The Bernoulli likelihood, flight by flight

\( p(y \mid x; \theta) = h_\theta(x)^{y} \big(1 - h_\theta(x)\big)^{1-y} \)

Each bar under the curve is one flight: the probability the model gave to what actually happened. Red flights had damage, blue did not. \(\ell(\theta)\) is the sum of the logs of the bars.

A confident wrong answer costs the most: a bar near zero has a log near minus infinity. At the maximum, the costliest flight is the one launched at 23.9°C: it was damaged, and the model gave damage only 8.5%.

Maximize It, and Meet an Old Friend

Update rule
\( \theta_j := \theta_j + \alpha \dfrac{\partial \ell(\theta)}{\partial \theta_j} \)

gradient ascent: we are maximizing

Derive
\( \theta := \theta + \alpha \sum_{i=1}^{m} \big( y^{(i)} - h_\theta(x^{(i)}) \big) x^{(i)} \)
Same as linear regression Different model, different noise, identical update. That is not a coincidence.

Part 3 of 6

One family

Why do linear and logistic regression share one update rule?

Generalized Linear Models

Gaussian \( \longrightarrow \) Linear regression
Bernoulli \( \longrightarrow \) Logistic regression
\( \theta := \theta + \alpha \sum_{i=1}^{m} \big( y^{(i)} - h_\theta(x^{(i)}) \big) x^{(i)} \)

Are there other distributions that lead to the same update rule?

The Exponential Family

The family of distributions for which we can derive the same update rule.

Exponential family \( p(y; \eta) = b(y) \exp\big\{ \eta^\top y - a(\eta) \big\} \)
  • \( b(y) \) is the base measure, and does not depend on \(\eta\)
  • \( a(\eta) \) is the log partition function, and does not depend on \(y\)
  • \( \eta \) is the natural parameter; \(\eta\) and \(y\) have the same dimensions, and \(a(\eta)\), \(y\) and \(b(y)\) are scalars here

Example 1: Bernoulli Becomes Logistic Regression

\( p(y; \phi) = \phi^{y} (1 - \phi)^{1-y} \)

Rewrite it in exponential-family form:

\( \displaystyle p(y; \phi) = \exp\left\{ y \underbrace{\log \frac{\phi}{1 - \phi}}_{\eta} + \underbrace{\log(1 - \phi)}_{-a(\eta)} \right\} \)
Read the natural parameter \( \eta = \log \dfrac{\phi}{1-\phi} \), so inverting gives \( \phi = \dfrac{1}{1 + e^{-\eta}} \): the sigmoid appears on its own.

Example 2: Gaussian Becomes Linear Regression

\( p(y; \mu) = \dfrac{1}{\sqrt{2\pi}} \exp\left\{ -\tfrac12 (y - \mu)^2 \right\} \)

Expanding the square and collecting terms:

\( \displaystyle p(y; \mu) = \underbrace{\frac{1}{\sqrt{2\pi}} e^{-y^2/2}}_{b(y)} \exp\left\{ \underbrace{\mu}_{\eta} y - \underbrace{\tfrac{\mu^2}{2}}_{a(\eta)} \right\} \)

The natural parameter is the mean, so the canonical response is the identity: a straight line.

Example 3: Poisson Becomes Log-Linear Regression

\( p(y; \lambda) = \dfrac{\lambda^{y} e^{-\lambda}}{y!}, \qquad y = 0, 1, 2, \dots \)

The Poisson distribution counts events in a fixed window when each happens independently of the others: earthquakes in a decade, clicks in an hour, typos on a page. \(\lambda\) is the expected count. Rewrite it in exponential-family form:

\( \displaystyle p(y; \lambda) = \underbrace{\frac{1}{y!}}_{b(y)} \exp\Big\{ \underbrace{\log \lambda}_{\eta} \, y - \underbrace{\lambda}_{a(\eta) \,=\, e^{\eta}} \Big\} \)
Read the natural parameter \( \eta = \log \lambda \), so \( \lambda = e^{\eta} \): the exponential appears on its own, as the sigmoid did for Bernoulli. Set \( \eta = \theta^\top x \) and a count model is \( \log \lambda = \theta^\top x \).

Why Do We Care?

\( p(y; \eta) = b(y) \exp\big\{ \eta^\top y - a(\eta) \big\} \)
\( \eta = \theta^\top x \)
Inference is easy
\( \mathbb{E}[y; \eta] = \dfrac{d\,a(\eta)}{d\eta} \)
\( \mathrm{Var}[y; \eta] = \dfrac{d^2 a(\eta)}{d\eta^2} \)
Mean and variance come from derivatives of one function.
Learning is easy The negative log-likelihood is convex in \(\theta\), so gradient steps find the global optimum.

One function holds the mean and the varianceTurn \(\eta\), and read both off the curve \(a(\eta)\)

Part 4 of 6

Counts

What if the answer counts something?

Data Type Chooses the Distribution

Assumption: \( p(y \mid x; \theta) \) is an exponential family.

Binary Bernoulli → logistic regression
Real Gaussian → linear regression
Counts Poisson → Poisson regression, today
Positive real Gamma, exponential
Distributions Dirichlet
The rule Pick the distribution that matches what \(y\) is, and the model follows.

How many earthquakes of each size?Every magnitude 5 and above on Earth, 2015 to 2024: 16,945 earthquakes

fit from

Each bar counts the earthquakes in one 0.1 slice of magnitude. The counts fall from hundreds to zero: no M 8.4 or larger happened in these ten years.

Data: US Geological Survey, ANSS Comprehensive Catalog, earthquake.usgs.gov/fdsnws/event/1/query, fetched 2026-09-28. Below M 5.5 half the magnitudes are body-wave estimates, which run low for large events; from M 6.0 almost all are moment magnitudes.

Reading a Poisson coefficient

\( \log \mu = \theta_0 + \theta_1 (M - 6) \quad\Longleftrightarrow\quad \mu = e^{\theta_0} \cdot \big(e^{\theta_1}\big)^{M - 6} \)

A linear model adds \(\theta_1\) for every unit of \(x\). A Poisson model multiplies the expected count by \(e^{\theta_1}\): on the log scale the line is straight, on the count scale it is a curve that never goes below zero.

A law, recovered Gutenberg and Richter (1944): about ten times fewer earthquakes for every unit of magnitude. The regression found \(e^{\theta_1} = 0.0997\) in ten years of data.

Poisson says the variance equals the mean. Year by year, earthquakes of M 7.0 to 7.4 average 9.0 with variance 9.1. Smaller ones come in aftershock swarms and vary more: M 6.0 to 6.4 average 91.6, variance 203.8.

Part 5 of 6

The recipe

What do all three models share, and what are the parts called?

Same loop, three modelsOnly \(h\) changes

Building a GLM

  • The natural parameter is linear in the inputs: \( \eta = \theta^\top x \). The predictor is a natural consequence, not a separate choice.
  • The prediction is the conditional mean: \( h_\theta(x) = \mathbb{E}[y \mid x; \theta] \)
  • Learning maximizes \( \log p(y \mid x; \theta) \); inference reads \( \mathbb{E}[y \mid x; \theta] \)
Update rule, always \( \theta := \theta + \alpha \sum_{i=1}^{m} \big( y^{(i)} - h_\theta(x^{(i)}) \big) x^{(i)} \)

Terminology

\(x\) \( \longrightarrow \) \( \theta^\top x \) \( \longrightarrow \) \( \eta \) \( \xrightarrow{\;g\;} \) \( h_\theta(x) \)
Names \(\theta\) model parameter · \(\eta\) natural parameter · \(\phi\) canonical parameter · \(g\) canonical response function · \(g^{-1}\) link function
Logistic regression, named \( h_\theta(x) = \mathbb{E}[y \mid x; \theta] \) and \( \phi = \dfrac{1}{1 + e^{-\eta}} = \dfrac{1}{1 + e^{-\theta^\top x}} \)

Part 6 of 6

In code

What does one GLM look like in ten lines of Python?

One function, two datasetsPress Run: this is real Python, in your browser


import numpy as np, pandas as pd

def fit_glm(X, y, h, alpha, steps=20000):
    theta = np.zeros(X.shape[1])
    for _ in range(steps):                       # the same update for every GLM
        theta += alpha * X.T @ (y - h(X @ theta)) / len(y)
    return theta

sigmoid = lambda z: 1 / (1 + np.exp(-z))

c = pd.read_csv('challenger_orings.csv')         # yes or no: Bernoulli, h = sigmoid
X = np.column_stack([np.ones(len(c)), c.temp_c - 20])
th = fit_glm(X, c.damage.values, sigmoid, alpha=0.05)
print('Challenger theta:', th.round(3), ' P(damage at -0.6 C):', sigmoid(th[0] + th[1] * (-0.6 - 20)).round(4))

q = pd.read_csv('usgs_quakes_m5_2015_2024.csv')  # a count: Poisson, h = exp
M = np.round(np.arange(6.0, 8.95, 0.1), 1)
y = np.array([(q.mag.round(1) == m).sum() for m in M])
X = np.column_stack([np.ones(len(M)), M - 6])
th = fit_glm(X, y, np.exp, alpha=0.01)
print('Earthquake theta:', th.round(3), ' ten times fewer? e^theta1 =', np.exp(th[1]).round(4))
    

You should get \(\theta = (-0.749, -0.417)\) and a 99.96% chance of damage, then \(\theta = (5.616, -2.306)\) and \(e^{\theta_1} = 0.0997\): the numbers on the slides. Try h = lambda z: z on a real-valued \(y\), and the same function is least squares.

Summary

The recipe
\( p(y; \eta) = b(y)\exp\{\eta^\top y - a(\eta)\} \)

choose the distribution that matches \(y\)

The link
\( \eta = \theta^\top x \)

the model is linear in the natural parameter

The update
\( \theta := \theta + \alpha \sum_i (y^{(i)} - h_\theta(x^{(i)})) x^{(i)} \)

the same for every member of the family

The lesson

least squares and cross-entropy were never two ideas.
They are one idea, seen through different distributions:
Gaussian, Bernoulli, and today Poisson.

What to take away

  1. The likelihood asks how probable the data is under the model. Least squares is its answer under Gaussian noise, cross-entropy its answer under Bernoulli noise.
  2. Zeros are data. The Challenger flights that went fine carry the pattern; leave them out and it disappears.
  3. Choose the distribution from what \(y\) is: a real number, a yes or no, a count. Its natural parameter \(\eta = \theta^\top x\) gives the model: the identity, the sigmoid, the exponential.
  4. One function \(a(\eta)\) holds the mean and the variance, and the update \(\theta := \theta + \alpha \sum_i (y^{(i)} - h_\theta(x^{(i)}))\,x^{(i)}\) is the same for every member of the family.
  5. A Poisson coefficient multiplies: \(e^{\theta_1} = 0.0997\) says ten times fewer earthquakes per unit of magnitude.