Machine Learning

Logistic Regression

Logistic regression turns a linear score into a probability, then learns a classification boundary by Bernoulli likelihood.

status: publishedimportance: criticaldifficulty 3/5math: undergraduateread: 17mlive demo

Concept Structure

Logistic Regression

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

3prerequisites
2next concepts
3related links

Learning map

Logistic Regression
BeforeLinear Regression & Least SquaresNow4/4 sections readyTryManipulate one control and predict the visible change.NextClassification Metrics, Thresholds, and Calibration

Object flow

4/4 sections readyAsk about thisResearch room
ConceptLogistic RegressionMachine Learning
2 sources attachedLocal snapshot ready
concept:machine-learning/logistic-regression

Conceptual Bridge

What should feel connected as you move through this page.

Carry inLinear Regression & Least Squares

Bring the mental model from Linear Regression & Least Squares; this page will reuse it instead of restarting from zero.

Work hereLogistic Regression

Logistic regression turns a linear score into a probability, then learns a classification boundary by Bernoulli likelihood.

Carry outClassification Metrics, Thresholds, and Calibration

The next edge should feel earned: use the demo prediction here before following Classification Metrics, Thresholds, and Calibration.

Test the linkManipulate one control and predict the visible change.Then continue to Classification Metrics, Thresholds, and Calibration
01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

Section prompt

You are here because many AI systems make categorical decisions from scores: a classifier scores labels, a language model scores tokens, and DPO scores preference pairs with a logistic loss. Logistic regression is the smallest honest version of that pattern.

Before this, know linear regression, maximum likelihood, and cross-entropy. By the end, you should be able to explain what a logit is, why the sigmoid creates a probability, and why the gradient for one example is qyq-y.

Linear regression predicts a number on the whole real line. Classification needs a probability between 00 and 11. Logistic regression keeps the linear score, then bends it through the sigmoid:

q=σ(z).q=\sigma(z).

The score zz is the logit. It can be any real number. The probability qq is constrained to the interval (0,1)(0,1).

The decision boundary is where the model is exactly unsure:

q=0.5.q=0.5.

For a one-dimensional model z=wx+bz=wx+b, this happens when wx+b=0wx+b=0. Changing ww changes the steepness and orientation. Changing bb shifts the boundary.

The most common misconception is that logistic regression is "linear regression with a squashed output." The output is squashed, but the training objective is different: it is Bernoulli likelihood, not squared error.

Another subtle caveat: the number qq is a model probability, not a promise that the fitted classifier is calibrated on future data. And with perfectly separable training data, unregularized logistic regression may keep increasing the weight norm instead of reaching a finite maximum-likelihood solution.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

Section prompt

For one example with features xRdx\in\mathbb R^d and binary label y{0,1}y\in\{0,1\}, define the linear score

z=wTx+b,z=w^{\mathsf T}x+b,

where wRdw\in\mathbb R^d and bRb\in\mathbb R. The predicted probability of label 11 is

q=Pθ(Y=1x)=σ(z)=11+ez.q=P_\theta(Y=1\mid x)=\sigma(z)=\frac{1}{1+e^{-z}}.

The Bernoulli likelihood for this example is

Pθ(yx)=qy(1q)1y.P_\theta(y\mid x)=q^y(1-q)^{1-y}.

The negative log-likelihood is

(z,y)=ylogq(1y)log(1q).\ell(z,y)=-y\log q-(1-y)\log(1-q).

This is binary cross-entropy, also called Bernoulli negative log-likelihood. Differentiating this loss through the sigmoid gives the compact logit gradient:

z=qy.\frac{\partial \ell}{\partial z}=q-y.

That single expression is the training signal. If y=1y=1 and qq is too small, then qy<0q-y<0, so gradient descent increases the logit. If y=0y=0 and qq is too large, then qy>0q-y>0, so gradient descent lowers the logit.

For a dataset with rows xiRdx_i\in\mathbb R^d, labels yi{0,1}y_i\in\{0,1\}, and probabilities qi=σ(wTxi+b)q_i=\sigma(w^{\mathsf T}x_i+b), the average loss is

L(w,b)=1ni=1n[yilogqi(1yi)log(1qi)].L(w,b)=\frac1n\sum_{i=1}^n\left[-y_i\log q_i-(1-y_i)\log(1-q_i)\right].

The gradients are

wL=1nXT(qy),\nabla_w L=\frac1n X^{\mathsf T}(q-y),

and

Lb=1ni=1n(qiyi).\frac{\partial L}{\partial b}=\frac1n\sum_{i=1}^n(q_i-y_i).

Here XRn×dX\in\mathbb R^{n\times d}, q,yRnq,y\in\mathbb R^n, and wRdw\in\mathbb R^d. The shape mirrors linear regression, but the residual-like term is probability error qyq-y, not numeric target error XwyXw-y.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

Section prompt
import numpy as np

# Binary logistic regression in one feature.
# Shapes: X is (n, 2), y is (n,), w is (2,).
x = np.array([-3, -2, -1, 0, 1, 2, 3], dtype=float)
y = np.array([0, 0, 0, 0, 1, 1, 1], dtype=float)
X = np.column_stack([np.ones_like(x), x])
w = np.array([-0.2, 0.7])

def sigmoid(z):
    return 1 / (1 + np.exp(-z))

def loss_and_grad(w):
    z = X @ w
    q = sigmoid(z)
    eps = 1e-12
    loss = -np.mean(y * np.log(q + eps) + (1 - y) * np.log(1 - q + eps))
    grad = X.T @ (q - y) / y.size
    return loss, grad, q

for step in range(60):
    loss, grad, q = loss_and_grad(w)
    w = w - 0.5 * grad

loss, grad, q = loss_and_grad(w)
print("bias, slope:", np.round(w, 3))
print("probabilities:", np.round(q, 3))
print("loss:", round(loss, 4))
print("gradient:", np.round(grad, 6))
print("decision boundary x:", round(-w[0] / w[1], 3))

The code mirrors the math: z = X @ w creates logits, q = sigmoid(z) creates probabilities, and X.T @ (q - y) / n is the gradient.

04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

Section prompt

Choose a point and inspect its current probability before revealing the logit-gradient direction. Predict whether training wants to raise that point's logit, lower it, or leave it mostly unchanged.

The curve shows q=σ(wx+b)q=\sigma(wx+b) over one feature. Points above the midline are positive examples; points below are negative examples. The reveal marks the selected point's contribution qyq-y and reports the average loss. Move the slope and bias to see how the same data can be underconfident, overconfident, or misclassified.

Live Concept Demo

Explore Logistic Regression

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 3/5undergraduatecode-aligned
Demo Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what Logistic Regression should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

Mechanism Storyboard

See the idea move before the page explains it

Logistic regression turns a linear score into a probability, then learns a classification boundary by Bernoulli likelihood.

Prediction open01 / Intuition
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Logistic Regression should make visible.

Visual Inquiry

Make the image answer a mathematical question

Logistic regression turns a linear score into a probability, then learns a classification boundary by Bernoulli likelihood.

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Logistic Regression easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

course-notes · 2023CS229 Lecture Notes: Logistic RegressionStanford CS229

Curriculum source for logistic regression as a Bernoulli GLM trained by likelihood.

Open source
book · 2016Deep LearningGoodfellow, Bengio, and Courville

Curriculum source for logits, sigmoid/softmax classifiers, and cross-entropy training.

Open source

Claim Review

Logistic regression turns a linear score into a probability, then learns a classification boundary by Bernoulli likelihood.

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources2 references

cs229-logistic-regression, goodfellow-2016-deep-learning

Witnesses4 local objects

Use equation, code, and demo objects to check whether the source support is operational.

Substantively reviewedBinary logistic regression maps a linear score through a sigmoid and trains by Bernoulli negative log-likelihood, whose logit gradient is predicted probability minus label.Claim metadata: source checked

CS229 supports the sigmoid hypothesis, Bernoulli likelihood, and log-likelihood gradient; Goodfellow supports sigmoid as a Bernoulli-parameter map and logistic regression as likelihood-trained classification. Together they support the page's NLL/BCE and q-y gradient convention.

Sources: CS229 Lecture Notes: Logistic Regression, Deep LearningThis source check covers binary logistic regression, not multinomial softmax regression, empirical calibration guarantees, cost-sensitive thresholding, or regularized solutions under perfect separation.A bounded review summary is present; still check caveats and exact source scope.

Checked CS229 section 2.1 and Goodfellow chapters 3/5. CS229 gives sigmoid, Bernoulli likelihood, log-likelihood, and gradient ascent (y-h)x; negating gives the page's BCE/NLL q-y descent signal. Goodfellow supports sigmoid as a Bernoulli parameter and logistic regression as likelihood-trained classification.

Reviewer: codex+gpt-pro-prior; reviewed 2026-06-28

Practice Loop

Try the idea before it explains itself

Logistic regression turns a linear score into a probability, then learns a classification boundary by Bernoulli likelihood.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in Logistic Regression.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Object research drawerClose
ConceptLogistic RegressionMachine Learning

Research Room

Attach the question to an exact object

Pick the concept, equation, source, code witness, claim, misconception, or demo state before asking for help. The handoff stays grounded to that object.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptMachine Learning

Logistic Regression

Anchored question

What is the smallest example that makes Logistic Regression click without losing the math?

Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays locally in this browser for concept:machine-learning/logistic-regression.

No local draft saved.
Evidence to inspect
  • Source ids to inspect: cs229-logistic-regression, goodfellow-2016-deep-learning
  • Definition, prerequisite, and contrast concept links
  • The equation or code witness that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Grounded AI handoff

I am working in Continuous Function's research reading room. Object: concept - Logistic Regression Object key: concept:machine-learning/logistic-regression Context: Machine Learning Anchor id: concept/concept-notebook/machine-learning/logistic-regression Open question: What is the smallest example that makes Logistic Regression click without losing the math? Evidence to inspect: - Source ids to inspect: cs229-logistic-regression, goodfellow-2016-deep-learning - Definition, prerequisite, and contrast concept links - The equation or code witness that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.

Open source object
concept/concept-notebook/machine-learning/logistic-regression concept:machine-learning/logistic-regression