Logistic regression
| Problem | Predict the probability of each class as a function of the features, with a linear decision boundary |
| Devised by | Pierre-François Verhulst (1838), the logistic function; Joseph Berkson (1944), the logit model; David Cox (1958), logistic regression; Daniel McFadden (1973), the multinomial model; Dong Liu and Jorge Nocedal (1989), L-BFGS |
| Accuracy | Gradient of the penalised log-loss below the tolerance ( by default) |
| Cost | per gradient evaluation for classes; typically 10–100 L-BFGS iterations |
| Read first | Linear regression: least squares, ridge, lasso and elastic net, Newton and quasi-Newton methods: Newton, BFGS and L-BFGS |
| API | LogisticRegression (fit, predict, predict_proba, coefficients, intercepts) |
Overview
Logistic regression models the log-odds of a class as a linear function of the features. For two classes, with the logistic function ; for classes the softmax generalises it,
The weights are fitted by maximum likelihood. The result is a linear classifier whose probabilities are calibrated when the model fits (without regularisation, the fitted probabilities average to the observed fraction of positives; with strong regularisation or a poorly matched boundary they need not, and a reliability plot is the way to check) and whose coefficients are interpretable: each unit of feature multiplies the odds by . It is the standard model for binary outcomes in medicine and the social sciences, and the output layer of most neural network classifiers.
Where it is used
Logistic regression predicts the probability of a yes/no outcome.
- Medicine. Risk scores for disease from patient measurements, and the odds ratios reported in clinical studies.
- Engineering and industry. Predicting whether a part will fail, a customer will respond or a message is spam.
- Communications. Soft decisions on bits are log-likelihood ratios, which are logistic.
- Neural networks. A logistic unit is a neuron, and the cross-entropy loss is the same.
History
Pierre-François Verhulst (1838) introduced the logistic curve to model population growth. Joseph Berkson (1944) proposed the “logit” as an alternative to the probit model of bioassay, and David Cox (1958) developed logistic regression for binary sequences. Daniel McFadden (1973) derived the multinomial logit from a theory of choice, work recognised by the 2000 Nobel prize in economics. Iteratively reweighted least squares (Newton’s method) was the classical fitting algorithm; for large problems quasi-Newton methods such as L-BFGS (Liu and Nocedal, 1989) took over.
The idea
The likelihood
From scores to probabilities. The model computes a linear score for each class, , and the softmax turns the scores into probabilities: exponentiating makes them positive, and dividing by the sum makes them add up to 1. A class with a higher score gets a higher probability. For two classes this reduces to the logistic function of the difference of the scores, which rises smoothly from 0 to 1.
Fitting by maximum likelihood. Given training data, how should the weights be chosen? The model assigns a probability to each possible label of each training point. The likelihood of the weights is the probability the model assigns to the labels that were actually observed, the product over the training points of , where and is the true class of point . Maximum likelihood chooses the weights that make the observed labels as probable as possible.
Products of many probabilities are tiny and awkward, so one works with the logarithm, which turns the product into a sum, and changes the sign to obtain a quantity to minimise. Averaged over the data this is the cross-entropy, or log-loss:
Each point contributes of the probability given to its true class: nothing if the model was certain and right, a little if it was fairly confident and right, and a great deal if it was confident and wrong.
The gradient. Differentiating through the softmax gives a remarkably simple result. For the weight of feature in class ,
where is 1 if point belongs to class and 0 otherwise. The bracket is the prediction error: the probability the model gave to class , minus what it should have been. The gradient is the average of the prediction errors, weighted by the feature values. It vanishes when the errors are uncorrelated with every feature.
The loss is convex, so any minimum is global and there are no false minima to be trapped in. But unlike least squares, setting the gradient to zero gives equations that cannot be solved in closed form, because the probabilities depend nonlinearly on the weights. An iterative solver is needed.
Separation and the penalty
Maximum likelihood has a failure mode that is easy to overlook. Suppose a hyperplane separates the classes perfectly in the training data. Then scaling the weights up makes the model more confident about every training point, all of which it classifies correctly, and the likelihood increases. Doubling the weights again increases it further. The likelihood has no maximum: it approaches its upper limit only as the weights grow without bound, and the fitted probabilities all tend to 0 or 1. This separation happens easily with many features and few samples.
The remedy is the one used in ridge regression: add an penalty on the weights (intercepts excluded) to the loss. The penalised minimum is unique and finite, and the less extreme probabilities it produces are better on new data:
Table 11.5. Effect of the penalty on logistic regression.
| L-BFGS iterations | training log-loss | test log-loss | test accuracy | ||
|---|---|---|---|---|---|
| 0 | 22 | 21.4 | 0.0000 | 5.187 | 0.694 |
| 0.0001 | 54 | 8.5 | 0.0012 | 2.204 | 0.683 |
| 0.001 | 51 | 5.8 | 0.0082 | 1.524 | 0.687 |
| 0.01 | 38 | 3.4 | 0.0468 | 0.938 | 0.693 |
| 0.1 | 22 | 1.4 | 0.1892 | 0.588 | 0.703 |
| 1 | 13 | 0.4 | 0.4391 | 0.603 | 0.673 |
40 training points in 30 dimensions (3 informative); test on 2000 points. The limit is 500 iterations.
Without a penalty the training loss falls to zero, the weights reach (and are still growing when the solver stops, because the loss no longer changes measurably) and the test log-loss is 5.2, confidently wrong. A moderate penalty barely changes the accuracy but improves the test log-loss ninefold.
Probability contours
Figure 11.4. Logistic regression contours.
For two classes the probability depends on only through the score , which is constant along lines perpendicular to . The decision boundary , where the score is zero, is therefore a straight line (a hyperplane in higher dimensions), and the other probability contours are lines parallel to it. Their spacing reflects the overlap of the classes: closely spaced contours mean a sharp transition, and so well-separated classes.
L-BFGS
The library minimises the penalised loss with L-BFGS: a quasi-Newton method that approximates the inverse Hessian from the last 10 pairs of steps and gradient changes, with a backtracking line search. It needs only the loss and gradient, and converges in a few dozen iterations on well-scaled data. Standardise the features first: badly scaled features slow it down.
Algorithm
Input: the training features (which should be standardised), the labels and the penalty .
- Initialise all weights and intercepts to zero, which gives every class the same probability.
- Evaluate the loss and its gradient at the current weights:
- compute the scores for every point and class;
- turn each row of scores into probabilities by the softmax. For numerical safety, subtract the row’s largest score from every score in the row first: this does not change the probabilities, and it keeps the exponentials from overflowing;
- the loss is the mean of plus the penalty ;
- the gradient is the mean of the prediction errors times the features, plus .
- Take an L-BFGS step: compute the search direction from the stored pairs, and backtrack along it from a unit step until the loss has decreased sufficiently (the Armijo condition).
- Test. Stop when the largest component of the gradient is below the tolerance, or when the loss has stopped changing; otherwise go to 2.
Each evaluation of the loss and gradient costs for points, features and classes.
Implementation
/// Penalised mean negative log-likelihood and its gradient with respect to the flattened weights.
fn objective(theta: &[f64], x: VR2D, labels: &[usize], classes: usize, l2: f64) -> (f64, Vec<f64>) {
let (n, p) = x.dim();
let w = R2D::from_shape_vec((classes, p + 1), theta.to_vec()).expect("shape");
let proba = softmax_rows(&w, x);
let mut loss = 0.0;
let mut grad = R2D::zeros((classes, p + 1));
for i in 0..n {
loss -= proba[[i, labels[i]]].max(1e-300).ln();
for c in 0..classes {
let err = proba[[i, c]] - f64::from(c == labels[i]);
for j in 0..p {
grad[[c, j]] += err * x[[i, j]];
}
grad[[c, p]] += err;
}
}
loss /= n as f64;
grad /= n as f64;
for c in 0..classes {
for j in 0..p {
loss += 0.5 * l2 * w[[c, j]] * w[[c, j]];
grad[[c, j]] += l2 * w[[c, j]];
}
}
(loss, grad.into_raw_vec_and_offset().0)
}
- The model is over-parameterised (adding a constant to every class’s weights changes nothing); the penalty selects the solution with . For two classes, the usual log-odds coefficients are the differences of the two rows.
In practice
//! Predict the probability of passing an exam from hours of study and hours of sleep.
use lib_jsl_core::R2D;
use lib_jsl_machine_learning::common::{Classifier, MlRng};
use lib_jsl_machine_learning::supervised::classification::LogisticRegression;
fn main() {
let mut rng = MlRng::new(3);
let n = 200;
let x = R2D::from_shape_fn((n, 2), |(_, j)| if j == 0 { rng.range(0.0, 10.0) } else { rng.range(4.0, 9.0) });
// True model: log-odds = -6 + 0.8 study + 0.5 sleep.
let passed: Vec<usize> = (0..n).map(|i| {
let z = -6.0 + 0.8 * x[[i, 0]] + 0.5 * x[[i, 1]];
(rng.uniform() < 1.0 / (1.0 + (-z).exp())) as usize
}).collect();
let mut model = LogisticRegression::new(1e-4).with_limits(2000, 1e-9);
model.fit(x.view(), &passed).unwrap();
// With two classes, the log-odds of class 1 are the difference of the two rows of weights.
let (w, b) = (model.coefficients(), model.intercepts());
println!("log-odds = {:+.2} {:+.2} study {:+.2} sleep ({} iterations)", b[1] - b[0], w[[1, 0]] - w[[0, 0]], w[[1, 1]] - w[[0, 1]], model.iterations());
let students = R2D::from_shape_vec((3, 2), vec![2.0, 8.0, 5.0, 7.0, 8.0, 5.0]).unwrap();
let p = model.predict_proba(students.view()).unwrap();
for i in 0..3 {
println!("study {:.0} h, sleep {:.0} h: P(pass) = {:.2}", students[[i, 0]], students[[i, 1]], p[[i, 1]]);
}
}
log-odds = -6.39 +0.92 study +0.41 sleep (22 iterations)
study 2 h, sleep 8 h: P(pass) = 0.22
study 5 h, sleep 7 h: P(pass) = 0.74
study 8 h, sleep 5 h: P(pass) = 0.95
The fitted log-odds recover the true model () to within sampling error from 200 students.
Strengths
- Probabilities, not just labels; interpretable coefficients; a convex problem with a unique penalised solution.
- Fast and reliable; the natural baseline for classification.
Weaknesses
- Linear decision boundaries (unless features are expanded); fails on problems such as the concentric circles.
- No standard errors or p-values for the coefficients.
- Only an penalty; no sparse () logistic regression.
Exercises
- Show that and derive the gradient of the binary cross-entropy.
- Show that the Hessian of the cross-entropy is positive semidefinite, so the loss is convex.
- Construct a separable data set and show that the unpenalised loss has no minimum.
- Show that the softmax model with is equivalent to binary logistic regression with .
- Implement Newton’s method (iteratively reweighted least squares) for binary logistic regression and compare its iteration count with L-BFGS.
Hints and answers
- . For cross-entropy with the gradient is .
- The Hessian is with , which is positive semidefinite.
- If a direction separates the classes, multiplying it by drives every term of the loss to zero without reaching it, so there is no minimum (the weights diverge).
- With , and .
- IRLS (Newton) takes a few iterations (typically 5 to 10) each costing a weighted least-squares solve; L-BFGS takes more iterations of lower cost each.
Further reading
- D. R. Cox, “The regression analysis of binary sequences”, Journal of the Royal Statistical Society B 20 (1958) 215–242.
- D. W. Hosmer, S. Lemeshow and R. X. Sturdivant, Applied Logistic Regression, 3rd ed., Wiley, 2013.
- D. C. Liu and J. Nocedal, “On the limited memory BFGS method for large scale optimization”, Mathematical Programming 45 (1989) 503–528.
- T. Hastie, R. Tibshirani and J. Friedman, The Elements of Statistical Learning, 2nd ed., Springer, 2009, section 4.4.