Level 3 In-Depth AI · Classical Machine Learning
Logistic Regression
The standard way to turn a weighted sum into a probability. Linear regression's score is squashed through an S-shaped curve so that it can answer yes-or-no questions, and its many-class version, softmax, sits at the end of almost every neural network.
- Level
- ●●●●● Easy
- Reading
- 13 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 10 concepts →
- Quiz
- 5 questions ↓
The full path from zero — 10 concepts before this one
- What Is AI?
- Derivatives and Slopes
- Vectors
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- Logistic Regression
Read them roughly in this order. See it on the concept map →
Why it matters
Many questions have a yes-or-no answer. Will this customer cancel? Is this card payment fraud? Is this tumour malignant? Will the patient be readmitted within 30 days? Logistic regression is the classic model for such questions. Despite the name it is a classification method: it predicts the probability that an example belongs to a class.
It is fast, it is reliable, and its weights can be read and explained, which is why it is still standard in medicine, credit scoring and online advertising, and why it is the baseline that any fancier classifier must beat. Its machinery also lives on inside deep learning. The last step of an image classifier, and the step where a language model picks its next token, is a softmax: logistic regression generalised to many classes. The loss that trains them, cross-entropy, is the one this chapter derives. Learn logistic regression and you have learned the output layer of GPT.
The intuition
Start from Linear Regression. It computes a weighted sum of the features, a score , which can be any number from minus infinity to plus infinity. A probability must lie between 0 and 1. So we need a function that takes any score and squashes it into that range, smoothly and in order: bigger score, bigger probability.
The function used is the sigmoid (or logistic function), an S-shaped curve. Very negative scores map to probabilities near 0, very positive ones to probabilities near 1, and a score of exactly 0 maps to 0.5, a coin toss.
Think of the score as accumulated evidence. Each feature adds or subtracts some evidence, weighted by how informative it is. The sigmoid then converts total evidence into a degree of belief. A little evidence either way leaves you near 50%. A lot pushes you towards certainty, but never quite all the way.
To make a yes-or-no decision, you pick a decision threshold, usually 0.5: predict "yes" when the probability is at least 0.5, which is the same as when the score is at least 0. The set of inputs where the score is exactly 0 is the decision boundary. Because the score is a weighted sum, that boundary is a straight line in two dimensions, a flat plane in three, and a hyperplane in more. Logistic regression is a linear classifier.
Key idea Logistic regression = linear regression's weighted sum, passed through the sigmoid to get a probability, trained with cross-entropy loss. Its decision boundary is a straight line (or flat plane). Softmax extends it to many classes.
How it works
The sigmoid
The sigmoid function, written ("sigma"), is:
Here is the base of natural logarithms. Check the key points: if , and . If is large, is tiny and . If is very negative, is huge and . The model is:
Read it as: the probability that the label is 1, given features , is the sigmoid of the score. The vertical bar means "given". The probability of class 0 is .
What the weights mean: odds and log-odds
The odds of an event are its probability divided by the probability that it doesn't happen: . A probability of 0.8 is odds of 4 (four to one). Undo the sigmoid and you find that the score is the logarithm of the odds:
This quantity is called the log-odds or logit. So logistic regression is really a linear regression on the log-odds. Each weight says how much the log-odds rise when its feature goes up by 1. Equivalently, raising a feature by 1 multiplies the odds by . Deep-learning code uses "logits" loosely to mean any raw scores before a sigmoid or softmax.
Training: cross-entropy
You can't use squared error well here (see Loss Functions). Instead, ask: which parameters make the labels we actually observed most probable? That is Maximum Likelihood Estimation. If the model gives probability to example being positive, the probability it gave to the observed label is when and when . Taking minus the average log of those gives binary cross-entropy:
Confident correct predictions cost almost nothing, and confident wrong ones cost a lot. There is no closed-form solution like linear regression's normal equation, so the loss is minimised iteratively, with Gradient Descent or a faster cousin. Fortunately the loss is convex, a single bowl with no false minima, and its gradient is strikingly simple:
It has the same shape as linear regression's: (prediction − label) × feature, averaged. The sigmoid's own derivative cancels neatly against the logarithm in the loss, which is one reason this pairing is used everywhere.
A worked example by hand
Four students practised for hours. The first two failed (), the last two passed (). Take , .
| Hours | Label | Score | Loss | ||
|---|---|---|---|---|---|
| 1 | 0 | −2.5 | 0.076 | 0.076 | |
| 2 | 0 | −1.0 | 0.269 | 0.269 | |
| 3 | 1 | 0.5 | 0.622 | −0.378 | |
| 4 | 1 | 2.0 | 0.881 | −0.119 |
The average loss is . All four are classified correctly at threshold 0.5. The decision boundary is where , at hours. The weight 1.5 means each extra hour multiplies the odds of passing by .
Now one gradient step. The gradient for averages : . For it averages : . With learning rate :
The loss drops from 0.248 to 0.221. Training repeats this until the loss stops falling. (On these four points it never does: see the first pitfall below.)
Decision boundaries in more dimensions
With two features the boundary is a straight line. The weight vector points perpendicular to it, towards the positive class. Lines of equal probability (10%, 90%) run parallel to the boundary. The larger the weights, the closer together they sit and the more abruptly the model switches from "no" to "yes".
A straight boundary can't separate classes arranged in a ring or a checkerboard. You can still use logistic regression there by adding engineered features such as or , just as polynomial features bend linear regression. Or you can switch to a model that learns curved boundaries itself: Decision Trees, kernel SVMs or Neural Networks.
Many classes: softmax regression
For classes (say cat, dog, bird), give each class its own weight vector and bias, and so its own score . Then turn the scores into probabilities that are positive and add up to 1 with the softmax function:
Exponentiate each score (which makes it positive), then divide by the total (which makes them sum to 1). For scores 2.0, 1.0 and 0.1: , , , total 11.21, so the probabilities are 0.659, 0.242 and 0.099.
This model is called softmax regression or multinomial logistic regression. Its loss is cross-entropy again: of the probability given to the true class. With two classes it reduces exactly to the sigmoid version. An older alternative is one-vs-rest: train separate yes/no classifiers ("cat or not?", "dog or not?") and pick the most confident.
Softmax is everywhere in deep learning. A language model's final layer is a softmax regression over a vocabulary of perhaps 100,000 tokens, applied to features computed by the The Transformer below it (Language Modeling and Next-Token Prediction, Decoding: Temperature, Top-k and Top-p).
In code
From scratch with NumPy on the breast-cancer dataset (569 tumours, 30 measurements each, label 1 = benign):
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
X, y = load_breast_cancer(return_X_y=True) # 569 tumours, 30 features
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)
mu, sd = X_tr.mean(axis=0), X_tr.std(axis=0)
X_tr, X_te = (X_tr - mu) / sd, (X_te - mu) / sd # standardise
def sigmoid(z):
return 1 / (1 + np.exp(-z))
w, b, lr = np.zeros(X.shape[1]), 0.0, 0.1
for step in range(1001):
p = sigmoid(X_tr @ w + b) # predicted P(benign)
loss = -np.mean(y_tr * np.log(p) + (1 - y_tr) * np.log(1 - p))
w -= lr * X_tr.T @ (p - y_tr) / len(y_tr) # gradient of cross-entropy
b -= lr * np.mean(p - y_tr)
if step % 250 == 0:
print(f"step {step:4d} loss {loss:.4f}")
pred = sigmoid(X_te @ w + b) >= 0.5
print("test accuracy:", np.mean(pred == y_te).round(3))
# step 0 loss 0.6931
# step 250 loss 0.0794
# step 500 loss 0.0684
# step 750 loss 0.0633
# step 1000 loss 0.0601
# test accuracy: 0.972
The first loss, 0.6931, is : with all weights zero every probability is 0.5. Note that the scaling statistics mu and sd come from the training set only (see Training, Validation and Test Sets).
With scikit-learn, for two classes and then three. predict_proba gives the probabilities, predict applies the 0.5 threshold.
from sklearn.datasets import load_breast_cancer, load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
# Two classes
X, y = load_breast_cancer(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)
clf = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_tr, y_tr)
print("P(benign) for 3 tumours:", clf.predict_proba(X_te[:3])[:, 1].round(3))
print("test accuracy:", round(clf.score(X_te, y_te), 3))
# Three classes: softmax regression on the iris flowers
X, y = load_iris(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)
clf = LogisticRegression(max_iter=1000).fit(X_tr, y_tr)
print("class probabilities:", clf.predict_proba(X_te[:1]).round(3))
print("weights shape:", clf.coef_.shape, " test accuracy:", round(clf.score(X_te, y_te), 3))
# P(benign) for 3 tumours: [0.001 0.96 0.999]
# test accuracy: 0.958
# class probabilities: [[0. 0.056 0.944]]
# weights shape: (3, 4) test accuracy: 0.974
The weight matrix for iris has shape (3, 4): one row of weights per class, one column per feature. Scikit-learn's LogisticRegression adds a small L2 penalty by default (C=1.0; smaller C means a stronger penalty), which is partly why its accuracy differs slightly from our unpenalised, briefly trained version. See Regularization: L1 and L2.
Common pitfalls
- Perfectly separable data. If a line separates the classes perfectly, as with our four students, the loss can always be lowered by making the weights bigger: the sigmoid gets steeper and the probabilities approach 0 and 1. Unpenalised training never stops, and the weights run off to infinity. A little Regularization: L1 and L2 fixes this, which is one reason libraries add it by default.
- Unscaled features. Gradient-based solvers converge slowly, or stop early with a
ConvergenceWarning, when features are on very different scales. Standardise inputs, or raisemax_iter. - Treating 0.5 as sacred. The threshold is a business decision. A cancer screen might flag anything above 0.1, a spam filter only above 0.99. Pick it on validation data using the costs of each kind of error (Evaluation Metrics).
- Imbalanced classes. With 1% positives, the model can reach 99% accuracy by never predicting positive. Look at precision and recall, and consider
class_weight="balanced". - Reading weights of correlated features. As in linear regression, correlated features share credit unpredictably. A weight's sign can even flip.
Watch out The probabilities are only trustworthy if the model is well specified and the training data looks like the data you predict on. A model trained on a balanced sample (50% fraud) will hugely overstate the chance of fraud in the real stream (0.1% fraud). Check calibration before acting on the numbers (Evaluation Metrics).
Where it leads
- Evaluation Metrics: precision, recall, ROC curves and calibration, all built on the probabilities logistic regression outputs.
- Regularization: L1 and L2: L1 and L2 penalties, essential for logistic regression with many features.
- Support Vector Machines: another linear classifier, trained with the hinge loss to maximise the margin.
- Naive Bayes: a probabilistic classifier that produces a similar linear boundary from very different assumptions.
- Neural Networks: a logistic regression on top of learned features. One sigmoid unit is an artificial neuron; see also the The Perceptron and Activation Functions.
- Language Modeling and Next-Token Prediction: next-token prediction is softmax regression over a vocabulary.
A bit of history
The logistic curve was introduced by the Belgian mathematician Pierre-François Verhulst in the 1830s and 1840s to model population growth that levels off. Joseph Berkson coined the word "logit" in 1944 and championed the logit model for dose–response experiments, in rivalry with the "probit" model built on the normal distribution. The statistician David Cox set out logistic regression for binary data in its modern form in 1958. Through the late 20th century it became the default tool in epidemiology, credit scoring and the social sciences. Natural-language-processing researchers rediscovered the multi-class version in the 1990s as the "maximum entropy" classifier, and with deep learning, softmax became the standard output layer of neural networks.
Try it
- Continue the worked example by hand for one more step from , . Does the decision boundary move?
- In the NumPy code, print the five features with the largest absolute weights (
np.argsort(-np.abs(w))[:5]andload_breast_cancer().feature_names). Do they make sense?- Use
clf.predict_probaon the breast-cancer test set with thresholds 0.3, 0.5 and 0.9. How many tumours are predicted malignant at each?Hint for 1: compute for , then the sigmoids. The boundary is at .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
MLU-Explain: Logistic Regression
A visual, interactive walk through the sigmoid, log-odds, the decision boundary and log loss.
An Introduction to Statistical Learning (with Python)
The friendliest rigorous introduction to classical ML, with Python labs. Free PDF.
StatQuest
Short, cheerful, very clear videos on statistics and nearly every ML algorithm.
Machine Learning Crash Course
Short, practical lessons with interactive visualisations covering regression, classification, embeddings and neural nets.
scikit-learn: Linear Models
The user-guide chapter on ordinary least squares, ridge, lasso, elastic net and logistic regression, with the maths and runnable examples.
Stanford CS229: Machine Learning
The classic mathematically rigorous ML course. Lecture notes and recorded lectures are free online.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/logistic-regression.md