Logistic Regression
Is this transaction fraud? Will this customer cancel? Is this tumour malignant? For a yes/no question you want more than a yes or no: you want a probability, so you can set a threshold that fits the cost of each kind of mistake. Logistic regression gives exactly that. Despite the name it is a classifier, the standard first model for binary problems, and the output layer of most neural-network classifiers. The Machine Learning course uses it through scikit-learn; here you derive the loss and fit it with Newton's method.
The model
Compute a linear score, then squash it into with the sigmoid:
Inverting the sigmoid shows what the linear part models: the log-odds,
So a weight means "one unit more of multiplies the odds by ". The decision boundary is where : a straight line in two dimensions, a hyperplane in general.
The loss: maximum likelihood
Treat each label as a coin flip with probability . The likelihood of the training labels is ; maximising it is the same as minimising the log-loss (binary cross-entropy):
Its gradient has the same shape as linear regression's, the error times the input:
The Hessian is positive semidefinite, so the loss is convex: no local minima to get stuck in. There is no closed form, but Newton's method converges in a handful of steps. Derivations: Maximum Likelihood Estimation, Maximum Likelihood and Cross-Entropy, Newton's Method.
scikit-learn regularises by default. It minimises
so is an inverse strength: small , strong regularisation. Without the penalty, perfectly separable data would push the weights to infinity.
From scratch with Newton's method
On the breast-cancer data (standardised on the training part), Newton's method on scikit-learn's objective:
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(return_X_y=True) # y = 1 means benign
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
sc = StandardScaler().fit(X_tr)
X_tr, X_te = sc.transform(X_tr), sc.transform(X_te)
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def objective(w, b, X, y, C):
z = X @ w + b
logloss = np.sum(np.logaddexp(0, z) - y * z) # sum of -log p(y_i), computed stably
return 0.5 * w @ w + C * logloss
def fit_logistic_newton(X, y, C=1.0, iters=8):
"""Newton's method on 1/2 ||w||^2 + C * sum log-loss (scikit-learn's objective)."""
Xb = np.column_stack([X, np.ones(len(y))]) # last column: intercept (not penalised)
theta = np.zeros(Xb.shape[1])
reg = np.eye(Xb.shape[1]); reg[-1, -1] = 0
for it in range(iters):
p = sigmoid(Xb @ theta)
grad = reg @ theta + C * Xb.T @ (p - y)
H = reg + C * (Xb.T * (p * (1 - p))) @ Xb
theta -= np.linalg.solve(H, grad)
print(f" iteration {it + 1} objective {objective(theta[:-1], theta[-1], X, y, C):.4f}")
return theta[:-1], theta[-1]
w, b = fit_logistic_newton(X_tr, y_tr)
sk = LogisticRegression(C=1.0, tol=1e-8, max_iter=10000).fit(X_tr, y_tr)
print("same weights as sklearn:", np.allclose(w, sk.coef_[0], atol=1e-3), np.isclose(b, sk.intercept_[0], atol=1e-3))
p = sigmoid(X_te @ w + b)
print("first 4 test probabilities of 'benign':", p[:4].round(3), " labels:", y_te[:4])
print("test accuracy ours", round(np.mean((p >= 0.5) == y_te), 3), " sklearn", round(sk.score(X_te, y_te), 3)) iteration 1 objective 102.0719
iteration 2 objective 60.8549
iteration 3 objective 41.3773
iteration 4 objective 31.3043
iteration 5 objective 27.7621
iteration 6 objective 27.0896
iteration 7 objective 27.0592
iteration 8 objective 27.0592
same weights as sklearn: True True
first 4 test probabilities of 'benign': [0.996 0. 0. 1. ] labels: [1 0 0 1]
test accuracy ours 0.958 sklearn 0.958
Newton's method reaches the minimum (objective 27.0592) in seven iterations, each solving one linear system, and the weights agree with scikit-learn's L-BFGS solver (run here with a tight tolerance so the comparison is fair). np.logaddexp(0, z) computes without overflow for large . Test accuracy on the 143 held-out tumours is 0.958. Most probabilities are close to 0 or 1: this data is nearly separable.
Nonlinear boundaries
The boundary of logistic regression is a hyperplane in feature space. Add polynomial features and it becomes a curve in the original space. In the lab, pick logistic regression on the moons and the circles data: the straight boundary cannot follow either shape. Lower to see the boundary tilt and soften as the weights shrink.
The same moons in code, with polynomial features of increasing degree and two strengths of regularisation, scored on a held-out half:
import numpy as np
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss
X, y = make_moons(n_samples=400, noise=0.25, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.5, random_state=0)
for degree in [1, 3, 9]:
for C in [1.0, 1000.0]:
m = make_pipeline(PolynomialFeatures(degree), StandardScaler(), LogisticRegression(C=C, max_iter=5000))
m.fit(X_tr, y_tr)
print(f"degree {degree} C {C:6.0f} train acc {m.score(X_tr, y_tr):.3f} test acc {m.score(X_te, y_te):.3f}"
f" test log-loss {log_loss(y_te, m.predict_proba(X_te)):.3f}")degree 1 C 1 train acc 0.880 test acc 0.885 test log-loss 0.320
degree 1 C 1000 train acc 0.875 test acc 0.875 test log-loss 0.323
degree 3 C 1 train acc 0.900 test acc 0.905 test log-loss 0.255
degree 3 C 1000 train acc 0.940 test acc 0.915 test log-loss 0.239
degree 9 C 1 train acc 0.935 test acc 0.905 test log-loss 0.234
degree 9 C 1000 train acc 0.935 test acc 0.920 test log-loss 0.277
Curved boundaries help (test accuracy 0.875 to 0.92). Accuracy alone hides a difference that the log-loss shows: degree 9 with almost no regularisation () has the best accuracy but a worse log-loss than with , because its probabilities are overconfident. When probabilities matter, judge a classifier by log-loss (or calibration), not only by accuracy. The noise in the moons caps accuracy around 0.9 whatever the model.
Hyperparameters
| Hyperparameter | Meaning |
|---|---|
C |
inverse regularisation strength (default 1.0); tune on a log grid |
penalty |
"l2" (default), "l1" (feature selection, with solver="liblinear" or "saga"), "elasticnet", None |
class_weight |
"balanced" reweights rare classes |
solver, max_iter, tol |
numerical settings; raise max_iter if you see a convergence warning |
Strengths, weaknesses, when to use it
Logistic regression trains fast, has a convex loss (one answer), outputs reasonably calibrated probabilities, and its coefficients read as odds ratios. It is limited to linear boundaries unless you engineer features, it needs scaled inputs for the penalty to be fair, and correlated features make individual coefficients unstable, as in linear regression. Use it as the first model and baseline for every classification problem, for scorecards and other settings where you must explain the model, and when you need probabilities rather than just labels.
Pitfalls
- Treating 0.5 as the only threshold. If missing a positive costs ten times a false alarm, a lower threshold is better; the probability lets you choose.
- Ignoring the default penalty.
LogisticRegression()is ridge-penalised with ; coefficients are shrunk. - Calling
expon raw scores. overflows for ; uselogaddexporscipy.special.expit.
Practice
- A credit model has for "number of late payments" (unscaled). What happens to the odds of default with two more late payments?
Answer
The log-odds rise by , so the odds are multiplied by . The probability itself changes by an amount that depends on where it started.
- Show that and explain where it appears in the Hessian.
Answer
, so . Differentiating the gradient once more gives , the diagonal matrix in .
Test yourself
What does logistic regression model as a linear function of the features?
- the probability
- the log-odds
- the class label
- the squared error
In scikit-learn's LogisticRegression, making C smaller…
- weakens the regularisation
- strengthens the regularisation
- changes the solver
- raises the decision threshold
Why is the log-loss of logistic regression easy to minimise reliably?
- It has a closed-form minimum
- It is convex, so any local minimum is the global one
- It is linear
- It has no gradient
Two models have the same test accuracy, but one has a much larger test log-loss. What does that tell you?
- Nothing; accuracy is what counts
- Its probabilities are worse, typically overconfident on the examples it gets wrong
- It is underfitting
- It was trained on less data