◆ AI All-in-One

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
↗ Plan a path here

Read first

Linear RegressionProbability Basics

This leads to

Neural NetworksEvaluation MetricsSupport Vector Machines
The full path from zero — 10 concepts before this one
  1. What Is AI?
  2. Derivatives and Slopes
  3. Vectors
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Supervised, Unsupervised and Reinforcement Learning
  8. Gradient Descent
  9. Supervised Learning
  10. Linear Regression
  11. 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 z=w⋅x+bz = \mathbf{w} \cdot \mathbf{x} + b, 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.

-6 -4 -2 0 2 4 6 0 0.5 1 score z = w·x + b probability σ(z) 1 h: p = 0.076 2 h: p = 0.269 3 h: p = 0.622 4 h: p = 0.881 Sigmoid σ(z) = 1 / (1 + e⁻ᶻ) squashes any score into (0, 1) Worked example w = 1.5, b = −4, x = hours green: passed (y = 1) red: failed (y = 0) σ(0) = 0.5 the decision threshold: z > 0 → predict class 1
Fig. 1 The sigmoid squashes any score into a probability between 0 and 1. The four dots are students from the worked example below: with w = 1.5 and b = −4, students who practised 1 and 2 hours get low pass probabilities, those who practised 3 and 4 hours high ones.

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 ("sigma"), is:

σ(z)=11+e−z\sigma(z) = \frac{1}{1 + e^{-z}}

Here e≈2.718e \approx 2.718 is the base of natural logarithms. Check the key points: if z=0z = 0, e0=1e^0 = 1 and σ=1/2\sigma = 1/2. If zz is large, e−ze^{-z} is tiny and σ≈1\sigma \approx 1. If zz is very negative, e−ze^{-z} is huge and σ≈0\sigma \approx 0. The model is:

p=P(y=1∣x)=σ(w⋅x+b)p = P(y = 1 \mid \mathbf{x}) = \sigma(\mathbf{w} \cdot \mathbf{x} + b)

Read it as: the probability that the label is 1, given features x\mathbf{x}, is the sigmoid of the score. The vertical bar means "given". The probability of class 0 is 1−p1 - p.

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: p/(1−p)p/(1-p). 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:

z=ln⁡p1−pz = \ln \frac{p}{1 - p}

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 ewe^{w}. 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 pip_i to example ii being positive, the probability it gave to the observed label is pip_i when yi=1y_i = 1 and 1−pi1 - p_i when yi=0y_i = 0. Taking minus the average log of those gives binary cross-entropy:

L(w,b)=−1N∑i=1N[ yiln⁡pi+(1−yi)ln⁡(1−pi) ]L(\mathbf{w}, b) = -\frac{1}{N}\sum_{i=1}^{N} \Big[\, y_i \ln p_i + (1 - y_i) \ln (1 - p_i) \,\Big]

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:

∂L∂w=1N∑i=1N(pi−yi) xi,∂L∂b=1N∑i=1N(pi−yi)\frac{\partial L}{\partial \mathbf{w}} = \frac{1}{N}\sum_{i=1}^{N} (p_i - y_i)\, \mathbf{x}_i, \qquad \frac{\partial L}{\partial b} = \frac{1}{N}\sum_{i=1}^{N} (p_i - y_i)

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 x=1,2,3,4x = 1, 2, 3, 4 hours. The first two failed (y=0y = 0), the last two passed (y=1y = 1). Take w=1.5w = 1.5, b=−4b = -4.

Hours xx Label yy Score z=1.5x−4z = 1.5x - 4 p=σ(z)p = \sigma(z) Loss p−yp - y
1 0 −2.5 0.076 −ln⁡(0.924)=0.079-\ln(0.924) = 0.079 0.076
2 0 −1.0 0.269 −ln⁡(0.731)=0.313-\ln(0.731) = 0.313 0.269
3 1 0.5 0.622 −ln⁡(0.622)=0.474-\ln(0.622) = 0.474 −0.378
4 1 2.0 0.881 −ln⁡(0.881)=0.127-\ln(0.881) = 0.127 −0.119

The average loss is (0.079+0.313+0.474+0.127)/4=0.248(0.079 + 0.313 + 0.474 + 0.127)/4 = 0.248. All four are classified correctly at threshold 0.5. The decision boundary is where 1.5x−4=01.5x - 4 = 0, at x=2.67x = 2.67 hours. The weight 1.5 means each extra hour multiplies the odds of passing by e1.5≈4.5e^{1.5} \approx 4.5.

Now one gradient step. The gradient for ww averages (p−y)×x(p - y) \times x: (0.076×1+0.269×2−0.378×3−0.119×4)/4=−0.249(0.076 \times 1 + 0.269 \times 2 - 0.378 \times 3 - 0.119 \times 4)/4 = -0.249. For bb it averages p−yp - y: (0.076+0.269−0.378−0.119)/4=−0.038(0.076 + 0.269 - 0.378 - 0.119)/4 = -0.038. With learning rate η=1\eta = 1:

w←1.5+0.249=1.749,b←−4+0.038=−3.962w \leftarrow 1.5 + 0.249 = 1.749, \qquad b \leftarrow -4 + 0.038 = -3.962

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 w1x1+w2x2+b=0w_1 x_1 + w_2 x_2 + b = 0 is a straight line. The weight vector w\mathbf{w} 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".

2 4 6 8 2 4 6 8 feature x₁ feature x₂ p = 0.1 p = 0.5 p = 0.9 Decision boundary p = 0.5 where w₁x₁ + w₂x₂ + b = 0: a straight line Dashed: p = 0.1 and 0.9 the probability changes smoothly across a band; far from the line the model is confident ● class 0 ■ class 1 fitted: w₁ = 1.91, w₂ = -0.97, b = -3.80 Arrow: the weight vector w points towards higher P(class 1), perpendicular to the boundary w
Fig. 2 Logistic regression on two features. The solid line is the decision boundary, where the predicted probability is 0.5. The dashed lines mark probabilities 0.1 and 0.9. The weight vector w is perpendicular to the boundary and points towards class 1.

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 x12x_1^2 or x1x2x_1 x_2, 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 KK classes (say cat, dog, bird), give each class its own weight vector and bias, and so its own score zk=wk⋅x+bkz_k = \mathbf{w}_k \cdot \mathbf{x} + b_k. Then turn the KK scores into KK probabilities that are positive and add up to 1 with the softmax function:

P(y=k∣x)=ezk∑j=1KezjP(y = k \mid \mathbf{x}) = \frac{e^{z_k}}{\sum_{j=1}^{K} e^{z_j}}

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: e2.0=7.39e^{2.0} = 7.39, e1.0=2.72e^{1.0} = 2.72, e0.1=1.11e^{0.1} = 1.11, total 11.21, so the probabilities are 0.659, 0.242 and 0.099.

Scores z cat 2.0 dog 1.0 bird 0.1 eᶻ cat 7.39 dog 2.72 bird 1.11 Probabilities cat 0.659 dog 0.242 bird 0.099 any real numbers all positive; sum = 11.21 divide by the sum: total = 1
Fig. 3 Softmax turns three raw scores into probabilities. Exponentiating makes every value positive and stretches the gaps; dividing by the sum makes them add up to 1. The highest score gets the largest share but not all of it.

This model is called softmax regression or multinomial logistic regression. Its loss is cross-entropy again: −ln⁡-\ln 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 KK 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 ln⁡2\ln 2: 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 raise max_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

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

  1. Continue the worked example by hand for one more step from w=1.749w = 1.749, b=−3.962b = -3.962. Does the decision boundary move?
  2. In the NumPy code, print the five features with the largest absolute weights (np.argsort(-np.abs(w))[:5] and load_breast_cancer().feature_names). Do they make sense?
  3. Use clf.predict_proba on 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 z=1.749x−3.962z = 1.749x - 3.962 for x=1..4x = 1..4, then the sigmoids. The boundary is at x=3.962/1.749x = 3.962/1.749.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A logistic regression gives a score z = 0 for an example. What probability does it predict?

  2. A weight of 1.5 on hours of practice. What happens to the odds of passing when practice goes up by one hour?

  3. For a cancer screen, missing a cancer is far worse than a false alarm. How should you set the decision threshold?

  4. Training data is perfectly separable by a line and you train without any penalty. What happens?

  5. Softmax turns scores 2.0, 1.0 and 0.1 into probabilities. Which is true of the result?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Interactive

MLU-Explain: Logistic Regression

Amazon Machine Learning University (MLU-Explain) · Beginner · Free

A visual, interactive walk through the sigmoid, log-odds, the decision boundary and log loss.

Video

StatQuest

Josh Starmer · Beginner · Free

Short, cheerful, very clear videos on statistics and nearly every ML algorithm.

Course

Machine Learning Crash Course

Google · Beginner · Free

Short, practical lessons with interactive visualisations covering regression, classification, embeddings and neural nets.

Docs

scikit-learn: Linear Models

scikit-learn · Intermediate · Free

The user-guide chapter on ordinary least squares, ridge, lasso, elastic net and logistic regression, with the maths and runnable examples.

Course

Stanford CS229: Machine Learning

Stanford University · Advanced · Free

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