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 ." 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.
- Logistic regression models , where is the sigmoid function.
- The sigmoid maps any real-valued linear score to a probability in , 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 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.
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 and label , it directly models the conditional distribution rather than the joint distribution of and . The model computes a linear combination of features, called the score or logit,
and then applies the sigmoid (logistic) function
to obtain a probability
The sigmoid is the right choice of "squashing function" for several converging reasons. First, it is a smooth, strictly increasing bijection from to , so any real-valued score becomes a valid probability without clipping or truncation. Second, it is the inverse of the logit (log-odds) function,
which means logistic regression is exactly the statement that log-odds are linear in the features:
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:
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 with , and writing , each label is modeled as a Bernoulli draw:
Assuming the examples are independent given their inputs, the likelihood of the whole dataset is
Maximizing is equivalent to maximizing its logarithm, and by convention we minimize the negative log-likelihood, which is exactly the binary cross-entropy loss:
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 , the gradient of with respect to collapses to a strikingly simple form:
The error term — predicted probability minus true label — is the "residual" of logistic regression, playing the same role that 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 , compute and classify if (equivalently, if ), else . The threshold 0.5 is a default; it can be moved to trade off precision and recall.
Complexity & correctness
Time complexity. Each gradient-descent iteration touches every training example once to compute a dot product of length and accumulate a -dimensional gradient update, giving work per iteration. Over iterations, full-batch gradient descent costs . Stochastic or mini-batch gradient descent instead updates on one example (or a small batch ) at a time, costing (or ) 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 : one dot product and one sigmoid evaluation.
Space complexity. Storing the parameters costs ; storing the dataset costs , which dominates in most regimes. Gradient descent needs no extra memory beyond one gradient vector of size , unlike methods that build an Gram matrix.
Why the optimization is easy: convexity. The cross-entropy loss is a convex function of . This follows from writing
using as the per-example loss. The term is linear in , hence convex (and concave). The term is the softplus function of ; its second derivative with respect to is , so softplus is strictly convex in , and composing a convex function with an affine map of preserves convexity. A sum of convex functions is convex, so is convex. Consequently:
- Any local minimum of 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
is positive semi-definite everywhere, another consequence of .
The linear-separability caveat. If the training data are perfectly linearly separable, the maximum-likelihood solution does not exist as a finite point: pushing in the separating direction drives every 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 makes the objective strictly convex and coercive, guaranteeing a unique finite minimizer for any .
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 versus pass/fail label .
| (hours) | (pass=1) |
|---|---|
| 0.5 | 0 |
| 1.0 | 0 |
| 1.5 | 0 |
| 3.0 | 1 |
| 3.5 | 1 |
| 4.0 | 1 |
Suppose after training (via the gradient descent loop above, several hundred iterations, ) we converge approximately to , (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.
| loss | ||||
|---|---|---|---|---|
| 0.5 | 0 | |||
| 1.0 | 0 | |||
| 1.5 | 0 | |||
| 3.0 | 1 | |||
| 3.5 | 1 | |||
| 4.0 | 1 |
Total loss , average nats per example — small, consistent with a well-separated dataset. Note the model does not report certainty ( or ) even though the classes are perfectly separated by ; it reports high but finite confidence, exactly because of the regularization (or early stopping) that prevents from blowing up as discussed above.
Gradient check at this point, to sanity-check convergence: take . Then , error . This example's contribution to is , a small positive number nudging slightly downward — but symmetric contributions from the points on the other side push upward by comparable amounts, and at convergence these very nearly cancel across the whole dataset, which is exactly the stationarity condition that gradient descent is driving toward.
Decision boundary. Setting : 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
| Pitfall | Why it happens | Fix |
|---|---|---|
| Using squared-error loss instead of cross-entropy | Looks similar to linear regression, but squared error on is non-convex in and has vanishing gradients when is near 0 or 1 | Always use cross-entropy (negative log-likelihood) for classification |
| Numerical overflow computing or | Naive sigmoid evaluation overflows for very negative or positive ; is undefined | Use a numerically stable sigmoid/log-sum-exp implementation; clip away from exactly 0 or 1 |
| Weights diverging on separable data | The MLE genuinely has no finite optimum when classes are linearly separable | Add L2/L1 regularization or use early stopping |
| Interpreting threshold as universally correct | Default threshold ignores class imbalance and asymmetric error costs | Tune the threshold using the ROC curve / precision-recall tradeoff for the task |
| Forgetting to standardize features | Features on very different scales make gradient descent slow and ill-conditioned | Standardize (zero mean, unit variance) before training |
| Treating the linear decision boundary as a modeling limitation that can't be lifted | Assumes logistic regression can only draw straight-line boundaries | Add 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
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.
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 and the parameters is linear, and the decision boundary is a linear (hyperplane) surface in feature space. But the relationship between and the predicted probability 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 and uses cross-entropy loss, which penalizes confident wrong predictions much more heavily than mild ones (the loss diverges as when ). 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 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 classes and applies the softmax function, , which generalizes the sigmoid to produce a full probability distribution over 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 ; 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 directly rather than modeling and 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 ) 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 ) 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.