Logistic Regression

Logistic Regression is a supervised learning algorithm that predicts the probability that an input belongs to one of two categories — despite its name, it is a classification algorithm, not a regression one. It is one of the most widely used models in machine learning due to its simplicity, interpretability, and surprising effectiveness on real-world problems. The counterintuitive fact: logistic regression is a linear model at heart, yet it can outperform far more complex models on many practical tasks, especially when data is limited.

The core insight

Logistic regression takes a linear combination of input features and squashes the result into a probability between 0 and 1 using the sigmoid function. Instead of asking "what number do I predict?", it asks "what is the probability this input belongs to class 1?" The "aha moment" is realising that by learning the right weights for each feature, the model learns a decision boundary — a line (or hyperplane) that separates two classes in your data. Everything else is just the mechanics of finding those weights.

How It Works

Logistic regression works in three steps: compute a weighted sum of the input features, pass that sum through the sigmoid function to get a probability, then use that probability to make a class prediction.

Step 1 — The Linear Combination

1
z=w1x1+w2x2+⋯+wnxn+b\quad z = w_1 x_1 + w_2 x_2 + \dots + w_n x_n + b

Explanation: Each input feature x is multiplied by a learned weight w, all terms are summed, and a bias b is added — this is identical to linear regression up to this point.

  • x1,x2,…,xnx_1, x_2, \dots, x_n — the input features (e.g., age, income, word counts)
  • w1,w2,…,wnw_1, w_2, \dots, w_n — learned weights, one per feature
  • bb — the bias term (shifts the decision boundary)
  • zz — the raw score, which can be any real number

Step 2 — The Sigmoid Function

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

Explanation: The sigmoid squashes any real number z into the range (0, 1), making it interpretable as a probability.

  • ee — Euler's number (~2.718)
  • σ(z)\sigma(z) — the predicted probability that the input belongs to class 1
  • When zz is very large, σ(z)≈1\sigma(z) \approx 1; when very negative, σ(z)≈0\sigma(z) \approx 0; when z=0z = 0, σ(z)=0.5\sigma(z) = 0.5

Step 3 — The Decision

3
y^={1if σ(z)≥0.50otherwise\quad \hat{y} = \begin{cases} 1 & \text{if } \sigma(z) \geq 0.5 \\ 0 & \text{otherwise} \end{cases}

Explanation: The predicted class y-hat is determined by whether the probability crosses the chosen threshold (0.5 by default).

Training — Log Loss The model is trained by minimising binary cross-entropy loss (also called log loss):

4
L=−1m∑i=1m[y(i)log⁡(p^(i))+(1−y(i))log⁡(1−p^(i))]\quad L = -\frac{1}{m}\sum_{i=1}^{m}\left[y^{(i)}\log(\hat{p}^{(i)}) + (1 - y^{(i)})\log(1 - \hat{p}^{(i)})\right]

Explanation: Log loss penalises the model heavily when it is confident but wrong, and lightly when it is uncertain — pushing the model to make well-calibrated probability predictions.

  • mm — number of training examples
  • y(i)y^{(i)} — the true label (0 or 1) for example ii
  • p^(i)\hat{p}^{(i)} — the predicted probability for example ii

Python Implementation ```python from sklearn.linear_model import LogisticRegression from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score, classification_report

# Load a real dataset data = load_breast_cancer() X, y = data.data, data.target

# Split into train/test sets X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42 )

# Feature scaling is important for logistic regression! scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test)

# Train the model model = LogisticRegression(max_iter=1000) model.fit(X_train, y_train)

# Predict classes and probabilities y_pred = model.predict(X_test) y_prob = model.predict_proba(X_test)[:, 1] # probability of class 1 print(f"Accuracy: {accuracy_score(y_test, y_pred):.3f}") print(classification_report(y_test, y_pred)) ``` ```python

# Understanding the threshold — changing it matters! import numpy as np

# Lower threshold: catch more positives (higher recall) custom_threshold = 0.3 y_pred_custom = (y_prob >= custom_threshold).astype(int) print(f"At threshold 0.3, accuracy: {accuracy_score(y_test, y_pred_custom):.3f}")

# Inspect learned weights — tells you which features matter most feature_names = data.feature_names weights = model.coef_[0] top_features = sorted(zip(feature_names, weights), key=lambda x: abs(x[1]), reverse=True)[:5] print("\nTop 5 most influential features:") for name, weight in top_features: direction = "↑ positive" if weight > 0 else "↓ negative" print(f" {name:35s} weight={weight:+.3f} ({direction})") ```

researcher · David Cox | b. 1924 – d. 2022 | Inventor of Logistic Regression

Sir David Cox was a British statistician and one of the most influential figures in 20th-century statistics, renowned for work spanning survival analysis, experimental design, and regression. In 1958, he published the landmark paper "The Regression Analysis of Binary Sequences" in the Journal of the Royal Statistical Society, which formally introduced logistic regression as a principled statistical method for modelling binary outcomes. Remarkably, Cox received the International Prize in Statistics (the statistical equivalent of the Nobel Prize) at the age of 93 in 2017, nearly 60 years after his most famous contribution.

Figure
Logistic Regression: From Input to Prediction
Logistic Regression: Data Flow INPUTS x₁ x₂ x₃ xₙ · WEIGHTED Σwᵢxᵢ+b = z (score) w₁ w₂ w₃ wₙ SIGMOID σ(z) OUTPUT p̂ = 0.82 probability threshold=0.5 → Class 1 features linear combo squash→(0,1) decide class
Figure
The Sigmoid Curve
The Sigmoid Function: σ(z) = 1 / (1 + e⁻ᶻ) z σ(z) 1.0 0.5 0.0 -6 -4 -2 0 2 4 6 σ(0)=0.5 ≈0 (class 0) ≈1 (class 1) decision boundary

Intuition

The Mental Model

Imagine you're a doctor trying to decide whether a tumour is malignant or benign. You look at several measurements: size, texture, symmetry. For each measurement, you have an intuition about how much it should "worry" you — a very large tumour worries you a lot, unusual texture worries you a bit. You add up all your weighted worries into a single overall score. Now, if that score is very high, you're almost certain it's malignant. If it's very low, you're almost certain it's benign. If it's right in the middle, you're uncertain. The sigmoid function is just a mathematical version of this intuition — it converts your "worry score" into a probability between 0% and 100%. The decision boundary is the line (or hyperplane in higher dimensions) where the model is exactly 50% confident. Points on one side get classified as class 1, points on the other as class 0. Training logistic regression is just the process of finding where to draw that line. Think of it like adjusting a recipe: the weights are how much of each ingredient to use, and gradient descent is the process of tasting the dish and adjusting the quantities until it tastes right — until your predictions match the true labels as often as possible.

Historical Development

Origins · 1 minhow this was discovered
History
1805
Adrien-Marie Legendre and Carl Friedrich Gauss develop the method of least squares, the conceptual ancestor of fitting curves to data — a prerequisite for regression thinking.
1838
Pierre François Verhulst introduces the logistic growth curve (the S-shaped curve) to model population growth, unknowingly providing the mathematical function that would later define logistic regression.
1944
Joseph Berkson introduces the term "logit" (the log-odds transformation) and proposes using it to model binary outcomes in biostatistics, laying direct groundwork for logistic regression.
1958
David Cox formally publishes logistic regression as a statistical method in "The Regression Analysis of Binary Sequences" (JRSS-B), establishing its theoretical foundations including maximum likelihood estimation.
1967
The method gains traction in medical research and epidemiology, where researchers begin using it to predict disease risk from patient characteristics — its first major application domain.
1972
Cox and Snell's work on generalised linear models unifies logistic regression under a broader mathematical framework alongside linear and Poisson regression.
1980
s–1990s: Logistic regression becomes a standard tool in statistics software packages (SAS, SPSS), dramatically widening its use in social science, economics, and clinical research.
2000
s: With the rise of machine learning, logistic regression is rediscovered as an efficient, interpretable baseline and becomes a standard component of ML libraries like scikit-learn (2007).
2010
s–present: Logistic regression underpins the final "readout layer" of many deep neural networks for classification, and remains the recommended first model to try on any binary classification problem.

Why It Matters

Real-World Impact
Email Spam FiltersEarly Gmail and Yahoo spam filters used logistic regression to classify emails as spam or not-spam, with features like word frequencies, sender reputation, and link counts as inputs — some production systems ran logistic regression on millions of emails per second due to its speed.
Medical Diagnosis and Risk ScoringThe APACHE II clinical scoring system (used in ICUs worldwide) and many cardiovascular risk calculators are logistic regression models — doctors use them daily to estimate patient mortality risk from lab values and vital signs.
Credit ScoringBanks and lenders use logistic regression to predict the probability of loan default from features like income, credit history, and debt-to-income ratio; it remains preferred over complex models because regulators require explainability.
A/B Testing in Tech CompaniesCompanies like Netflix, Airbnb, and Booking.com use logistic regression to model click-through rates and conversion probabilities in controlled experiments, because interpretable coefficients directly reveal which UI changes drive user behaviour.
Natural Language Processing — Sentiment AnalysisBefore transformer models dominated NLP, logistic regression with TF-IDF features was the standard baseline for sentiment classification (positive/negative reviews), and still rivals neural networks on small datasets.
Fraud DetectionPayPal and Stripe use logistic regression as one layer in their fraud detection pipelines; its probabilistic outputs integrate naturally with downstream decision systems and risk thresholds that can be adjusted for different fraud cost trade-offs.
Advertising Click-Through Rate PredictionFacebook and Google's early ad ranking systems used logistic regression at massive scale (billions of predictions per day) to estimate whether a user would click an ad — demonstrating that a simple model with the right features can match complex alternatives at scale.

Prerequisites

What This Leads To

See Also

Linear Regression · Decision Trees · Naive Bayes · Cross-Entropy Loss · Gradient Descent

Before this

Where this leads