Logistic Regression and the Sigmoid

A hospital wants to predict whether a tumor is malignant from its size and texture. It wants not just a number but a probability. Linear Regression and the Least Squares Objective can fit a line through 0/1 labels. But its output can drift below 0 or above 1, which makes no sense as a probability. It also treats a hugely-confident wrong prediction the same way it treats a mild misfit. Logistic regression fixes this by squashing a linear score through a smooth S-shaped curve, the sigmoid. This ensures the output always lands in (0, 1). It can then be read as an honest probability estimate. This idea sits at the heart of applied machine learning. Spam filters, credit-default models, click-through-rate prediction, medical diagnosis, and A/B test analysis all rely on it. They rest on some version of logistic regression. This holds either directly or as the last layer of a much larger neural network. Its appeal is a rare combination. The model is linear in its parameters, so it is fast to fit and easy to interpret. Yet it produces calibrated probabilities and a genuinely probabilistic notion of "how sure am I." The big picture is that logistic regression reframes classification as conditional probability estimation. Instead of asking "which side of a boundary is this point on," we ask "what is P(y=1∣x)P(y=1 \mid x)." We then choose parameters that make the observed labels as likely as possible under that model. The decision boundary — the classification you actually output — falls out as a byproduct. It comes from thresholding that probability, typically at 0.5. This article builds the model from first principles. It explains why the sigmoid is the natural link function. It shows how to fit it by Gradient Descent for Parameter Estimation on a likelihood-based objective. It also shows how to reason about its complexity and correctness. Finally, it places the model among the family of classifiers that follow it. These include Maximum Likelihood and Cross-Entropy Loss, Linear Discriminant Analysis, and Support Vector Machines and Maximum Margin.

Key takeaways
  • Logistic regression models P(y=1∣x)=σ(w⊤x+b)P(y=1\mid x) = \sigma(w^\top x + b), where σ\sigma is the sigmoid function.
  • The sigmoid maps any real-valued linear score to a probability in (0,1)(0,1), fixing the range problem of linear regression on 0/1 labels.
  • Parameters are fit by maximizing the likelihood of the observed labels, equivalently minimizing the cross-entropy (log) loss.
  • The loss is convex in the weights, so gradient descent (or Newton's method) converges to a global optimum.
  • The decision boundary w⊤x+b=0w^\top x + b = 0 is linear, even though the probability surface is curved.
  • It generalizes naturally to multiple classes (softmax regression) and forms the output layer of many neural networks.
The core insight

Logistic regression predicts class probability by passing a linear score through the sigmoid function, then fits parameters by maximizing the likelihood of the observed labels — a convex problem with a linear decision boundary.

The idea

Logistic regression is a discriminative probabilistic model for binary classification: given input x∈Rdx \in \mathbb{R}^d and label y∈{0,1}y \in \{0, 1\}, it directly models the conditional distribution P(y∣x)P(y \mid x) rather than the joint distribution of xx and yy. The model computes a linear combination of features, called the score or logit,

z=w⊤x+b,z = w^\top x + b,

and then applies the sigmoid (logistic) function

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

to obtain a probability

P(y=1∣x;w,b)=σ(w⊤x+b),P(y=0∣x;w,b)=1−σ(w⊤x+b).P(y = 1 \mid x; w, b) = \sigma(w^\top x + b), \qquad P(y=0\mid x; w,b) = 1 - \sigma(w^\top x + b).

The sigmoid is the right choice of "squashing function" for several converging reasons. First, it is a smooth, strictly increasing bijection from R\mathbb{R} to (0,1)(0,1), so any real-valued score becomes a valid probability without clipping or truncation. Second, it is the inverse of the logit (log-odds) function,

logit⁡(p)=log⁡p1−p,\operatorname{logit}(p) = \log\frac{p}{1-p},

which means logistic regression is exactly the statement that log-odds are linear in the features:

log⁡P(y=1∣x)P(y=0∣x)=w⊤x+b.\log \frac{P(y=1\mid x)}{P(y=0\mid x)} = w^\top x + b.

This is the defining structural assumption of the model — not that the probability itself is linear (it cannot be, since probabilities are bounded), but that the log-odds are. Third, the sigmoid arises naturally as the posterior class probability whenever the class-conditional feature distributions belong to the exponential family with equal dispersion (for example, two Gaussians with a shared covariance matrix), which is exactly the generative assumption behind Linear Discriminant Analysis; logistic regression can be seen as directly modeling that same functional form without committing to the generative assumptions. A key algebraic fact used throughout the derivation is the sigmoid's self-referential derivative:

σ′(z)=σ(z)(1−σ(z)).\sigma'(z) = \sigma(z)\big(1 - \sigma(z)\big).

This single identity is what makes the gradient of the training objective come out so cleanly.

How it works

Setting up the likelihood. Given a training set {(xi,yi)}i=1n\{(x_i, y_i)\}_{i=1}^n with yi∈{0,1}y_i \in \{0,1\}, and writing pi=σ(w⊤xi+b)p_i = \sigma(w^\top x_i + b), each label is modeled as a Bernoulli draw:

P(yi∣xi)=piyi(1−pi)1−yi.P(y_i \mid x_i) = p_i^{y_i} (1-p_i)^{1-y_i}.

Assuming the examples are independent given their inputs, the likelihood of the whole dataset is

L(w,b)=∏i=1npiyi(1−pi)1−yi.L(w,b) = \prod_{i=1}^n p_i^{y_i}(1-p_i)^{1-y_i}.

Maximizing LL is equivalent to maximizing its logarithm, and by convention we minimize the negative log-likelihood, which is exactly the binary cross-entropy loss:

J(w,b)=−∑i=1n[yilog⁡pi+(1−yi)log⁡(1−pi)].J(w,b) = -\sum_{i=1}^n \Big[ y_i \log p_i + (1-y_i)\log(1-p_i) \Big].

This is the same objective foreshadowed in Maximum Likelihood and Cross-Entropy Loss: fitting logistic regression is maximum-likelihood estimation of a Bernoulli model with a linear-in-logit mean function.

Computing the gradient. Using the chain rule and σ′(z)=σ(z)(1−σ(z))\sigma'(z) = \sigma(z)(1-\sigma(z)), the gradient of JJ with respect to ww collapses to a strikingly simple form:

∇wJ=∑i=1n(pi−yi) xi,∂J∂b=∑i=1n(pi−yi).\nabla_w J = \sum_{i=1}^n (p_i - y_i)\, x_i, \qquad \frac{\partial J}{\partial b} = \sum_{i=1}^n (p_i - y_i).

The error term (pi−yi)(p_i - y_i) — predicted probability minus true label — is the "residual" of logistic regression, playing the same role that (y^i−yi)(\hat y_i - y_i) plays in ordinary least squares. This is no coincidence: both are instances of generalized linear models, where the gradient of the negative log-likelihood always takes the form (residual) × (feature vector).

Fitting by gradient descent. Because there is no closed-form solution (unlike ordinary least squares), parameters are fit iteratively, exactly as in Gradient Descent for Parameter Estimation: ``` Input: data {(x_i, y_i)}_{i=1..n}, learning rate eta, iterations T, L2 penalty lambda >= 0 Initialize w <- 0 (vector of length d), b <- 0 for t = 1 .. T: grad_w <- 0 (vector), grad_b <- 0 for i = 1 .. n: z_i <- dot(w, x_i) + b p_i <- 1 / (1 + exp(-z_i)) # sigmoid error_i <- p_i - y_i grad_w <- grad_w + error_i x_i grad_b <- grad_b + error_i grad_w <- grad_w + lambda w # optional L2 regularization w <- w - eta grad_w / n b <- b - eta grad_b / n if ||grad_w|| < tolerance and |grad_b| < tolerance: break return w, b ``` Two practical notes are folded into the pseudocode. First, `1 / (1 + exp(-z_i))` should be computed with a numerically stable formulation (e.g. branching on the sign of `z_i`) to avoid overflow for large negative `z_i`. Second, an L2 penalty `lambda * ||w||^2` is commonly added to the loss to prevent the weights from diverging to infinity on linearly separable data — a subtlety explained under correctness below. At inference time, given a new xx, compute p=σ(w⊤x+b)p = \sigma(w^\top x + b) and classify y^=1\hat y = 1 if p≥0.5p \ge 0.5 (equivalently, if w⊤x+b≥0w^\top x + b \ge 0), else y^=0\hat y = 0. The threshold 0.5 is a default; it can be moved to trade off precision and recall.

Figure
From linear score to class probability: the sigmoid squashing map
z = wᵀx + b σ(z) 0.5 0.0 1.0 z = 0 → p = 0.5 features x z = wᵀx+b linear score σ(z) sigmoid squash to (0,1) p = P(y=1∣x) threshold at 0.5

Complexity & correctness

Time complexity. Each gradient-descent iteration touches every training example once to compute a dot product of length dd and accumulate a dd-dimensional gradient update, giving O(nd)O(nd) work per iteration. Over TT iterations, full-batch gradient descent costs O(Tnd)O(Tnd). Stochastic or mini-batch gradient descent instead updates on one example (or a small batch bb) at a time, costing O(d)O(d) (or O(bd)O(bd)) per step, trading a noisier gradient for far cheaper individual updates — the same tradeoff described generally in Gradient Descent for Parameter Estimation. Prediction on a new point costs O(d)O(d): one dot product and one sigmoid evaluation.

Space complexity. Storing the parameters costs O(d)O(d); storing the dataset costs O(nd)O(nd), which dominates in most regimes. Gradient descent needs no extra memory beyond one gradient vector of size O(d)O(d), unlike methods that build an n×nn \times n Gram matrix.

Why the optimization is easy: convexity. The cross-entropy loss J(w,b)J(w, b) is a convex function of (w,b)(w, b). This follows from writing

J(w,b)=∑i[log⁡(1+ew⊤xi+b)−yi(w⊤xi+b)],J(w,b) = \sum_i \Big[ \log(1 + e^{w^\top x_i + b}) - y_i (w^\top x_i + b) \Big],

using log⁡(1+ez)−yz\log(1+e^{z}) - yz as the per-example loss. The term −yi(w⊤xi+b)-y_i(w^\top x_i + b) is linear in (w,b)(w,b), hence convex (and concave). The term log⁡(1+ez)\log(1+e^z) is the softplus function of z=w⊤xi+bz = w^\top x_i + b; its second derivative with respect to zz is σ(z)(1−σ(z))>0\sigma(z)(1-\sigma(z)) > 0, so softplus is strictly convex in zz, and composing a convex function with an affine map of (w,b)(w,b) preserves convexity. A sum of convex functions is convex, so JJ is convex. Consequently:

  • Any local minimum of JJ is a global minimum.
  • Gradient descent with a sufficiently small, fixed or decaying learning rate is guaranteed to converge toward a global minimum (or, in degenerate cases discussed below, toward the boundary of the feasible region).
  • Second-order methods (Newton–Raphson, i.e. Iteratively Reweighted Least Squares) converge locally at a quadratic rate because the Hessian
H=∑ipi(1−pi) xixi⊤H = \sum_i p_i(1-p_i)\, x_i x_i^\top

is positive semi-definite everywhere, another consequence of σ(z)(1−σ(z))≥0\sigma(z)(1-\sigma(z)) \ge 0.

The linear-separability caveat. If the training data are perfectly linearly separable, the maximum-likelihood solution does not exist as a finite point: pushing ∥w∥→∞\|w\| \to \infty in the separating direction drives every pip_i toward the correct label (0 or 1), decreasing the loss without bound but never reaching a minimizer. This is not a bug in the algorithm — the loss genuinely has no finite minimizer — and is why L2 (or L1) regularization is standard practice: adding λ∥w∥2\lambda \|w\|^2 makes the objective strictly convex and coercive, guaranteeing a unique finite minimizer for any λ>0\lambda > 0.

Honest tradeoffs. Logistic regression assumes a linear decision boundary in the original (or transformed) feature space; if the true boundary is curved, the model underfits unless you engineer nonlinear features or use basis expansions/kernels. It also implicitly assumes the log-odds are linear, an assumption that can fail even when a linear boundary would suffice, requiring diagnostic checks (e.g., partial residual plots) in careful applied work. Compared to Linear Discriminant Analysis, logistic regression makes fewer distributional assumptions (it is discriminative, not generative) and tends to be more robust when class-conditional distributions are non-Gaussian, at the cost of being less efficient (statistically) when the generative assumptions genuinely hold.

Worked example

Consider a tiny 1-D dataset: hours studied xx versus pass/fail label yy.

xx (hours)yy (pass=1)
0.50
1.00
1.50
3.01
3.51
4.01

Suppose after training (via the gradient descent loop above, several hundred iterations, η=0.5\eta = 0.5) we converge approximately to w≈2.0w \approx 2.0, b≈−4.5b \approx -4.5 (illustrative rounded values; exact numbers depend on the optimizer path, but this is close to what gradient descent finds on this data). Let's trace predictions and the per-example loss contribution at this fitted point.

xxz=2.0x−4.5z = 2.0x - 4.5p=σ(z)p = \sigma(z)yyloss =−[ylog⁡p+(1−y)log⁡(1−p)]= -[y\log p + (1-y)\log(1-p)]
0.5−3.5-3.50.0290.0290−log⁡(0.971)≈0.029-\log(0.971) \approx 0.029
1.0−2.5-2.50.0760.0760−log⁡(0.924)≈0.079-\log(0.924) \approx 0.079
1.5−1.5-1.50.1820.1820−log⁡(0.818)≈0.201-\log(0.818) \approx 0.201
3.01.51.50.8180.8181−log⁡(0.818)≈0.201-\log(0.818) \approx 0.201
3.52.52.50.9240.9241−log⁡(0.924)≈0.079-\log(0.924) \approx 0.079
4.03.53.50.9710.9711−log⁡(0.971)≈0.029-\log(0.971) \approx 0.029

Total loss ≈0.618\approx 0.618, average ≈0.103\approx 0.103 nats per example — small, consistent with a well-separated dataset. Note the model does not report certainty (p=0p=0 or p=1p=1) even though the classes are perfectly separated by x=2.25x = 2.25; it reports high but finite confidence, exactly because of the regularization (or early stopping) that prevents ∥w∥\|w\| from blowing up as discussed above.

Gradient check at this point, to sanity-check convergence: take x=1.5,y=0x = 1.5, y = 0. Then p=0.182p = 0.182, error =p−y=0.182= p - y = 0.182. This example's contribution to ∂J/∂w\partial J/\partial w is 0.182×1.5=0.2730.182 \times 1.5 = 0.273, a small positive number nudging ww slightly downward — but symmetric contributions from the y=1y=1 points on the other side push ww upward by comparable amounts, and at convergence these very nearly cancel across the whole dataset, which is exactly the stationarity condition ∇wJ≈0\nabla_w J \approx 0 that gradient descent is driving toward.

Decision boundary. Setting z=0z = 0: 2.0x−4.5=0⇒x=2.252.0x - 4.5 = 0 \Rightarrow x = 2.25 hours. Any student studying more than 2.25 hours is predicted to pass; this threshold is the model's single learned "cutoff," and the smooth sigmoid around it quantifies how confident that cutoff is at intermediate study times.

Common pitfalls & traps

PitfallWhy it happensFix
Using squared-error loss instead of cross-entropyLooks similar to linear regression, but squared error on σ(z)\sigma(z) is non-convex in (w,b)(w,b) and has vanishing gradients when pip_i is near 0 or 1Always use cross-entropy (negative log-likelihood) for classification
Numerical overflow computing e−ze^{-z} or log⁡(1−p)\log(1-p)Naive sigmoid evaluation overflows for very negative or positive zz; log⁡(0)\log(0) is undefinedUse a numerically stable sigmoid/log-sum-exp implementation; clip pp away from exactly 0 or 1
Weights diverging on separable dataThe MLE genuinely has no finite optimum when classes are linearly separableAdd L2/L1 regularization or use early stopping
Interpreting p=0.5p=0.5 threshold as universally correctDefault threshold ignores class imbalance and asymmetric error costsTune the threshold using the ROC curve / precision-recall tradeoff for the task
Forgetting to standardize featuresFeatures on very different scales make gradient descent slow and ill-conditionedStandardize (zero mean, unit variance) before training
Treating the linear decision boundary as a modeling limitation that can't be liftedAssumes logistic regression can only draw straight-line boundariesAdd polynomial/interaction features or basis functions to get curved boundaries while keeping the linear-in-logit structure

Pioneers & history

The logistic function itself predates machine learning by over a century, originating in 19th-century population-growth models, but its use for statistical classification and its marriage with maximum-likelihood estimation is what created modern logistic regression.

Origins · 1 minPierre François Verhulst and how this was discovered
PF
Pierre François Verhulst
1804–1849 · Belgian mathematician who introduced the logistic function to model constrained population growth

Verhulst proposed the logistic differential equation in the 1830s–40s to correct the unbounded exponential growth model of Malthus, producing the S-shaped curve that saturates at a carrying capacity. This same curve, a full century later, would become the canonical link function for binary classification, its saturating shape making it exactly the right tool for turning unbounded scores into bounded probabilities.

History
1838
— Verhulst introduces the logistic function for bounded population growth.
1944
— Joseph Berkson coins the term "logit" and champions logistic regression over the probit model for bioassay data.
1958
— David Cox formalizes logistic regression as a general regression method for binary outcome data.
1970
s — Logistic regression becomes standard in epidemiology and biostatistics for odds-ratio estimation in case-control studies.
1980
s–2000s — Logistic regression is adopted across statistics, econometrics, and machine learning as a baseline classifier and as the output layer of neural networks.

Where this matters

Logistic regression is the workhorse baseline of applied predictive modeling: credit scoring and loan-default models at banks, click-through-rate and conversion-rate prediction in online advertising, spam and fraud detection, and clinical risk scores (like predicting readmission or disease risk) all commonly start from — and often ship — a regularized logistic regression, prized for being fast, interpretable (coefficients have an odds-ratio interpretation), and well-calibrated. In modern deep learning, the sigmoid and its multi-class generalization, the softmax, are the near-universal final layer for classification networks, converting the last linear layer's raw scores into probabilities, and the cross-entropy loss derived here is the loss function trained by backpropagation in essentially every classifier network. The same mathematics also underlies logistic components of generalized linear models used throughout applied statistics, and it is the natural jumping-off point for comparing decision-boundary philosophies against Linear Discriminant Analysis (generative, Gaussian-based) and Support Vector Machines and Maximum Margin (margin-based, non-probabilistic by default).

Ask the tutor: How would the training dynamics and final decision boundary change if I used the hinge loss instead of cross-entropy on this same linear score?

Is logistic regression a linear model or a nonlinear model?

Both, in different senses. The relationship between the score z=w⊤x+bz = w^\top x + b and the parameters is linear, and the decision boundary z=0z=0 is a linear (hyperplane) surface in feature space. But the relationship between zz and the predicted probability p=σ(z)p = \sigma(z) is nonlinear — that's precisely the point of the sigmoid, which bends an unbounded line into a bounded, S-shaped probability curve. So logistic regression is usually classified as a "linear classifier" because its boundary is linear, even though its probability output is a nonlinear function of the input.

How does logistic regression differ from linear regression on 0/1 labels?

Fitting ordinary least squares directly to 0/1 labels can produce predictions below 0 or above 1, which are meaningless as probabilities, and it weights all residuals equally regardless of how confident the model already is. Logistic regression instead applies the sigmoid to keep outputs in (0,1)(0,1) and uses cross-entropy loss, which penalizes confident wrong predictions much more heavily than mild ones (the loss diverges as p→0p \to 0 when y=1y=1). The result is a model whose outputs are interpretable as calibrated probabilities and whose optimization is convex, unlike squared error applied to a sigmoid output.

Why does the loss function use the negative log-likelihood instead of the likelihood directly?

Maximizing the likelihood L(w,b)=∏ipiyi(1−pi)1−yiL(w,b) = \prod_i p_i^{y_i}(1-p_i)^{1-y_i} directly is numerically unstable because it multiplies many small probabilities together, quickly underflowing to zero. Taking the logarithm converts the product into a sum, which is numerically stable and preserves the same maximizer since log is monotonically increasing. Flipping the sign turns "maximize log-likelihood" into "minimize negative log-likelihood," matching the standard convention that optimization algorithms like gradient descent are typically framed as minimization.

Can logistic regression handle more than two classes?

Yes, through a generalization called softmax regression (or multinomial logistic regression). Instead of one sigmoid output, the model computes a linear score for each of KK classes and applies the softmax function, softmax(z)k=ezk/∑jezj\text{softmax}(z)_k = e^{z_k} / \sum_j e^{z_j}, which generalizes the sigmoid to produce a full probability distribution over KK classes. The loss generalizes correspondingly to categorical cross-entropy, and the same convexity and gradient-descent machinery carries over essentially unchanged.

Does logistic regression require the features to be Gaussian or satisfy other distributional assumptions?

No — this is one of its main selling points over generative alternatives like Linear Discriminant Analysis. Logistic regression makes no assumption about the distribution of the features xx; it only assumes that the log-odds of the label are a linear function of the features. This makes it a discriminative model: it models P(y∣x)P(y\mid x) directly rather than modeling P(x∣y)P(x\mid y) and P(y)P(y) and applying Bayes' rule, which is what generative classifiers do.

What role does regularization play beyond preventing divergence on separable data?

Beyond guaranteeing a finite solution on separable data, L2 regularization (ridge-style penalty λ∥w∥2\lambda\|w\|^2) shrinks coefficients toward zero, reducing variance and improving generalization when features are correlated or numerous relative to the sample size. L1 regularization (lasso-style penalty λ∥w∥1\lambda\|w\|_1) additionally drives some coefficients to exactly zero, performing implicit feature selection. Both are typically tuned via cross-validation, trading a small increase in training loss for a reduction in overfitting on held-out data.

How does logistic regression relate to a single-layer neural network?

Logistic regression is exactly a neural network with no hidden layers: one linear layer producing a score, followed by a sigmoid activation and cross-entropy loss. This is why the sigmoid/softmax plus cross-entropy combination reappears as the standard output layer in deep networks — every deep classifier is, in a sense, "logistic regression on top of learned features," where the earlier layers of the network learn a nonlinear feature transformation and the final layer performs logistic (or softmax) regression on top of it.

Before this

Where this leads