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.
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
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.
- — the input features (e.g., age, income, word counts)
- — learned weights, one per feature
- — the bias term (shifts the decision boundary)
- — the raw score, which can be any real number
Step 2 — The Sigmoid Function
Explanation: The sigmoid squashes any real number z into the range (0, 1), making it interpretable as a probability.
- — Euler's number (~2.718)
- — the predicted probability that the input belongs to class 1
- When is very large, ; when very negative, ; when ,
Step 3 — The Decision
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):
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.
- — number of training examples
- — the true label (0 or 1) for example
- — the predicted probability for example
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})") ```
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.
Intuition
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
Why It Matters
Prerequisites
What This Leads To
See Also
Linear Regression · Decision Trees · Naive Bayes · Cross-Entropy Loss · Gradient Descent