Sub topic 2
Fitting Logistic Regression by Maximum Likelihood
Assume you know basic probability, derivatives, NumPy, and train/test splits. This chapter connects the probability model to its training algorithm.
From likelihood to log loss
For each example, logistic regression predicts \(pi=P(yi=1\mid xi)\). A Bernoulli likelihood assigns probability \(pi\) when \(yi=1\), and \(1-pi\) when \(y_i=0\):
\[ P(yi\mid xi)=pi^{yi}(1-pi)^{1-yi}. \]
The likelihood of the complete dataset is the product of these terms. Maximum likelihood chooses weights that make the observed labels most probable. Products are inconvenient, so we maximize the log likelihood. Equivalently, we minimize its negative average, called log loss or binary cross-entropy:
\[ L=-\frac{1}{n}\sumi[yi\log pi+(1-yi)\log(1-p_i)]. \]
Gradient descent and its gradient
Gradient descent repeatedly moves parameters opposite the loss gradient. For \(p=\operatorname{sigmoid}(Xw+b)\), the batch gradients are:
\[ \nablaw L=\frac{X^T(p-y)}{n},\qquad \nablab L=\operatorname{mean}(p-y). \]
import numpy as np
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def fit(X, y, learning_rate=0.1, steps=1000):
n, d = X.shape
w = np.zeros(d)
b = 0.0
for _ in range(steps):
p = sigmoid(X @ w + b)
error = p - y
w -= learning_rate * (X.T @ error) / n
b -= learning_rate * error.mean()
return w, b
X = np.array([[-2.0], [-1.0], [1.0], [2.0]])
y = np.array([0, 0, 1, 1])
w, b = fit(X, y)
print(w, b)Scaling and regularization
Feature scaling puts numeric features on comparable ranges. Without it, a large-scale feature can dominate updates, making learning slow or unstable. Standardization subtracts each feature’s mean and divides by its standard deviation.
Regularization adds a penalty to the loss:
| Penalty | Added term | Typical effect | Column | Column |
|---|---|---|---|---|
| L2 | \(\lambda\sum_j w_j^2\) | Shrinks weights smoothly | ||
| L1 | \(\lambda\sum_j | w_j | \) | Can set weights exactly to zero |
Exclude the intercept from the penalty unless you have a specific reason to penalize it.
Coefficient interpretation
A coefficient \(wj\) changes the log-odds by \(wj\) for a one-unit increase in feature \(x_j\), holding other features fixed. Exponentiating gives the odds ratio:
\[ \text{odds ratio}=e^{w_j}. \]
With standardized features, this describes a one-standard-deviation increase.
Exercise
If a coefficient is 0.69, approximately what happens to the odds after a one-unit increase in its feature?
Show answer
The odds are multiplied by exp(0.69), approximately 2. A one-unit increase doubles the odds, holding other features fixed.