Curriculum02. Supervised LearningLesson 2 of 7

Logistic Regression

The sigmoid link function, log-odds, and linear decision boundaries.

20 min readIntermediateModule 02
01 // CORE INTUITION

Core Intuition: Squashing Unbounded Scores

A linear score z=wTx+bz = \mathbf{w}^T \mathbf{x} + b can output −12.4-12.4 or +47.8+47.8. Probabilities cannot fall below 00 or exceed 11.

Logistic regression bends that straight line into a smooth S-curve using the sigmoid function σ(z)\sigma(z). Far to the left (z≪0z \ll 0), σ(z)\sigma(z) hugs 00; far to the right (z≫0z \gg 0), it saturates near 11; right on the boundary (z=0z = 0), it outputs exact uncertainty: 0.50.5.

Takeaway:Logistic regression wraps a linear score inside the sigmoid S-curve to guarantee valid probability outputs between 0 and 1.
02 // THE PROBLEM IT SOLVES

The Problem It Solves: Calibrated Binary Decisions

Fitting Ordinary Least Squares directly to binary labels y∈{0,1}y \in \{0, 1\} produces predictions below 00 or above 11, and a single confident positive outlier drags the entire line sideways.

Engineers need calibrated probabilities for risk scoring (fraud probability, patient malignancy risk, email spam odds) so downstream systems can adjust decision thresholds based on real misclassification costs.

Takeaway:Use logistic regression when you need a fast, interpretable linear classifier that outputs calibrated probabilities.
03 // STEP-BY-STEP MECHANISM

Step-by-Step Mechanism: Log-Odds to Decision Threshold

Logistic regression runs in three deterministic stages:

1. Compute Linear Log-Odds: Evaluate z(i)=wTx(i)+bz^{(i)} = \mathbf{w}^T \mathbf{x}^{(i)} + b, which models the log-odds ln⁡p1−p\ln\frac{p}{1-p}.

2. Apply Sigmoid Link: Convert z(i)z^{(i)} into predicted probability p^(i)=σ(z(i))\hat{p}^{(i)} = \sigma(z^{(i)}).

3. Optimize Log Loss & Threshold: Adjust w,b\mathbf{w}, b via gradient descent (or L-BFGS) to minimize binary cross-entropy, then predict class 1 whenever p^(i)≥τ\hat{p}^{(i)} \ge \tau.

Takeaway:The linear equation predicts log-odds; the sigmoid maps log-odds to probabilities; threshold τ\tau turns probabilities into class labels.
04 // INTERACTIVE SANDBOX

Interactive Sandbox: Sigmoid Boundary & Threshold Trade-Off

Adjust the weight slope (w1w_1), bias (bb), and decision threshold (τ\tau) sliders in the visualizer.

Watch how shifting τ\tau translates the separating boundary across feature space without retraining weights, trading False Positives against False Negatives and updating Accuracy, Precision, Recall, and Binary Cross-Entropy in real time.

Sigmoid Log-Odds & Threshold Engine
LOG LOSS: 0.201ACC: 100%P: 1.00 | R: 1.00

Slide probability threshold τ\tau to translate the linear boundary across feature space without retraining weights, or tune w1w_1 and bb to lower Binary Cross-Entropy.

THRESHOLD (τ)0.50
WEIGHT (w₁)1.4
BIAS (b)-6.8
TP: 5
FP: 0
TN: 5
FN: 0
134.512.54Feature x₁Feature x₂
Class 0
Class 1
Boundary σ(z) = 0.50
Misclassified
Takeaway:Changing threshold τ\tau shifts the decision boundary laterally, trading Precision against Recall without modifying learned weights.
05 // MATHEMATICAL FORMULATION

Mathematical Formulation: Binary Cross-Entropy Loss

Pairing Mean Squared Error with σ(z)\sigma(z) creates flat non-convex plateaus where gradients vanish. Binary Cross-Entropy derives directly from Maximum Likelihood Estimation of a Bernoulli distribution, keeping J(w,b)J(\mathbf{w}, b) strictly convex with a clean gradient 1mXT(p^−y)\frac{1}{m}\mathbf{X}^T(\hat{\mathbf{p}} - \mathbf{y}).

PRIMARY OBJECTIVE FORMULATION
Variable & Symbol Definitions
J(w,b)J(\mathbf{w}, b)Average Binary Cross-Entropy (log loss) over mm training samples
y(i)y^{(i)}Ground-truth binary label in {0,1}\{0, 1\} for sample ii
p^(i)\hat{p}^{(i)}Predicted probability σ(wTx(i)+b)∈(0,1)\sigma(\mathbf{w}^T \mathbf{x}^{(i)} + b) \in (0, 1)
ln⁡\lnNatural logarithm penalizing confident wrong predictions exponentially
Takeaway:Binary Cross-Entropy keeps logistic optimization convex and cancels sigmoid saturation in the gradient.
06 // KEY ASSUMPTIONS

Key Assumptions: Linear Log-Odds & Independence

Logistic regression relies on three structural conditions:

1. Linearity in Log-Odds: Input features combine linearly to shift ln⁡(p/(1−p))\ln(p / (1-p)). Circular or XOR patterns require engineered polynomial or interaction features.

2. Independent Observations: Training rows must be sampled independently without repeated correlated measurements.

3. Low Multicollinearity: Highly correlated features destabilize weight estimates unless L2 regularization (CC) constrains weight magnitude.

Takeaway:Standard logistic regression draws only flat hyperplane boundaries unless you supply non-linear basis features.
07 // COMMON PITFALLS

Common Pitfalls: Separable Weight Explosion & Threshold Traps

If two classes are perfectly linearly separable and regularization is disabled, logistic regression pushes ∥w∥→∞\|\mathbf{w}\| \to \infty so σ(z)\sigma(z) approaches exact 00 and 11, causing numerical overflow and brittle overconfidence.

In imbalanced tasks (such as 99.5 percent legitimate transactions), keeping default τ=0.5\tau = 0.5 often yields 99.5 percent accuracy while catching zero fraud cases.

Algorithmic Checkpoint

In a cancer screening classifier, you lower the decision threshold from tau = 0.50 down to tau = 0.25. What happens to False Negatives and Recall?

Takeaway:Always apply L2 regularization to bound weights and tune threshold τ\tau using Precision-Recall trade-offs rather than assuming 0.5.
08 // COMPLEXITY

Computational Complexity: Iterative Optimization

Because the log-loss gradient equations are transcendental, logistic regression has no closed-form matrix inverse solution. Training with L-BFGS or gradient descent runs in O(k⋅m⋅d)O(k \cdot m \cdot d) time across kk iterations with O(m⋅d)O(m \cdot d) memory.

At serving time, inference computes one dot product and one exponential, running in O(d)O(d) operations and making it fast enough for sub-millisecond ad ranking and API scoring.

Takeaway:Training scales linearly in samples and iterations O(k⋅m⋅d)O(k \cdot m \cdot d), while inference runs in O(d)O(d) time.
09 // REAL-WORLD USE

Real-World Use: Click-Through Prediction & Risk Scoring

Large-scale advertising platforms, credit underwriting teams, and clinical triage tools rely on L2-regularized logistic regression when probability calibration and feature attribution matter.

Each coefficient wjw_j translates directly into an odds-ratio multiplier ewje^{w_j}, letting regulators and engineers inspect how each input raises or lowers predicted risk.

Takeaway:Logistic regression remains a standard baseline in finance, medicine, and click prediction due to calibrated probabilities and interpretable odds ratios.
10 // PRODUCTION CODE

Production Code: NumPy & scikit-learn

Implement sigmoid gradient descent in NumPy and thresholded probability scoring with scikit-learn LogisticRegression.

Production Implementation
import numpy as np

def sigmoid(z: np.ndarray) -> np.ndarray:
    return 1.0 / (1.0 + np.exp(-np.clip(z, -50, 50)))

def fit_logistic(X: np.ndarray, y: np.ndarray, lr: float = 0.2, steps: int = 400):
    m, d = X.shape
    w = np.zeros(d)
    b = 0.0
    for _ in range(steps):
        p = sigmoid(X @ w + b)
        err = p - y
        w -= lr * (X.T @ err) / m
        b -= lr * np.mean(err)
    return w, b

X = np.array([[1.0, 1.0], [1.5, 1.2], [3.5, 3.8], [4.0, 4.2]])
y = np.array([0, 0, 1, 1])
w, b = fit_logistic(X, y)
probs = sigmoid(X @ w + b)
print("Probabilities:", np.round(probs, 3))
Implementation Walkthrough:

The NumPy loop clips z to [-50, 50] to prevent exp overflow and steps down the exact log-loss gradient (p - y). In scikit-learn, wrapping StandardScaler with LogisticRegression(C=1.0) keeps L2 regularization balanced across features, and .predict_proba(X)[:, 1] returns calibrated probabilities for custom thresholding.

Takeaway:Use predict_proba with domain-calibrated thresholds rather than relying blindly on .predict() at 0.5.