Part 3 — Supervised Learning Lesson 15 / 56
Estimated Reading: 15–18 mins Level: Intermediate

Logistic Regression: Classification from Probabilities

From Continuous Linear Scores to Calibrated Probabilities, Log-Odds, Binary Cross-Entropy, and Threshold Optimization

Core Learning Objectives

Distinguish classification boundaries from regression trends; formulate the Sigmoid activation function to map real scores into calibrated probabilities $(0, 1)$; understand Odds, Log-Odds (Logit), and interpret multiplicative coefficient effects ($e^{w_j}$); derive the Binary Cross-Entropy loss function and understand why Mean Squared Error fails; evaluate models beyond accuracy using Confusion Matrices, Precision, Recall, F1-Score, and ROC-AUC; build production pipelines in Scikit-Learn; and tune decision thresholds on imbalanced datasets.

1. Introduction: From Numerical Estimation to Categorical Decision-Making

In the preceding lessons, we mastered Linear Regression and Polynomial Regression. Both algorithms solve regression problems where the target output $y$ is a continuous numerical quantity—such as apartment price (BDT Lakh) or vehicle braking distance (meters).

However, a massive proportion of industrial machine learning problems do not demand continuous numbers. Instead, they require making categorical decisions between discrete choices:

  • E-commerce Conversion: Will a visitor browsing laptops complete a checkout or abandon the cart? ($\text{Buy} = 1, \text{No Buy} = 0$)
  • Cybersecurity: Is an incoming email legitimate communication or malicious phishing? ($\text{Spam} = 1, \text{Ham} = 0$)
  • Fintech Fraud Detection: Is a BDT 50,000 credit card transaction authentic or fraudulent? ($\text{Fraud} = 1, \text{Authentic} = 0$)
  • Healthcare Diagnostics: Does a patient biopsy scan indicate malignant tumor pathology or benign tissue? ($\text{Malignant} = 1, \text{Benign} = 0$)

These challenges constitute Binary Classification Problems. Despite containing the historical word "Regression" in its name, Logistic Regression is fundamentally the foundational, standard classification algorithm in machine learning. It models the conditional probability $P(y = 1 \mid \mathbf{x})$ that a given observation belongs to the positive category.

2. Why Not Simple Linear Regression? The Mathematical Failure

A novice engineer might ask: "Why can't we simply encode our binary target as $0$ and $1$, and fit a standard Ordinary Least Squares linear regression line $\hat{y} = \mathbf{w}^T \mathbf{x} + b$?"

Applying standard Linear Regression to classification triggers three catastrophic mathematical and practical failures:

1. Unbounded Prediction Outputs ($y \notin [0, 1]$) A straight line extends to $\pm \infty$. For high feature values (e.g. high customer income), linear regression will produce predictions like $\hat{y} = 1.65$ or $\hat{y} = -0.42$. Probabilities cannot be negative or greater than 100%!
2. Catastrophic Decision Boundary Skew from Outliers OLS minimizes squared residuals. If a single customer with a massive income ($x = 500,000$) buys the product ($y = 1$), OLS penalizes the distance between $1$ and $5.0$, tilting the entire regression line and shifting the $0.5$ cutoff point, destroying predictions for normal customers!
3. Severe Heteroscedasticity (Violation of Constant Variance) For binary outcomes, the variance of residuals is mathematically $p(1 - p)$, which varies with $x$. This breaks Gauss-Markov assumptions, rendering statistical confidence intervals completely invalid.
Dimension Linear Regression Logistic Regression
Core Task Continuous Numerical Value Estimation Discrete Category & Probability Estimation
Output Domain $\hat{y} \in (-\infty, +\infty)$ $\hat{p} \in (0, 1)$
Model Equation $\hat{y} = \mathbf{w}^T \mathbf{x} + b$ $\hat{p} = \sigma(\mathbf{w}^T \mathbf{x} + b) = \frac{1}{1 + e^{-(\mathbf{w}^T \mathbf{x} + b)}}$
Loss Function Mean Squared Error ($\text{MSE}$) Binary Cross-Entropy / Log Loss ($\text{BCE}$)
Outlier Sensitivity Extreme (Line tilts violently) Robust (Sigmoid asymptotes saturate at 0 and 1)

3. The Two-Step Engine: Linear Score & The Sigmoid Function

Logistic Regression solves classification through an elegant two-step architecture:

1 Step 1: Compute Unbounded Linear Score ($z$)

First, the model computes a standard dot product between the input features and learned weights, adding a bias term. This produces a linear score $z$ (also known as the Logit):

$$z = b + w_1 x_1 + w_2 x_2 + \dots + w_p x_p = \mathbf{w}^T \mathbf{x} + b$$

The score $z$ can take any real value: $-\infty \lt z \lt +\infty$. High positive values suggest strong positive class evidence; large negative values suggest negative class evidence.

2 Step 2: Squashing through the Sigmoid Activation Function ($\sigma$)

Next, to convert the unbounded score $z$ into a mathematically valid probability, Logistic Regression passes $z$ through the Sigmoid Function (standard logistic function):

$$\sigma(z) = \frac{1}{1 + e^{-z}} = \frac{e^z}{1 + e^z}$$

Where $e \approx 2.71828$ is Euler's number. The Sigmoid function bends the straight score into a smooth S-curve, compressing $(-\infty, +\infty)$ strictly into $(0, 1)$.

Bounded Range For any $z \in \mathbb{R}$, $0 \lt \sigma(z) \lt 1$. It never outputs negative values or values exceeding 1.0.
Neutral Origin Calibration When $z = 0$, $\sigma(0) = \frac{1}{1 + e^0} = \frac{1}{2} = 0.50$ (50% neutral uncertainty).
Derivative Elegance Its derivative is computationally trivial: $\sigma'(z) = \sigma(z)(1 - \sigma(z))$, accelerating gradient descent.

4. Decision Thresholds: Converting Probabilities to Hard Actions

Once the model outputs a probability estimate $\hat{p} = P(y = 1 \mid \mathbf{x})$, how does it make a binary classification decision? It compares the probability against a Decision Threshold ($\tau$):

$$\hat{y} = \begin{cases} 1 & \text{if } P(y = 1 \mid \mathbf{x}) \ge \tau \\ 0 & \text{if } P(y = 1 \mid \mathbf{x}) \lt \tau \end{cases}$$

By default, binary classifiers apply $\tau = 0.50$. If a customer's purchase probability is $52\%$, they are labeled "Buyer" ($1$); if $48\%$, "Non-buyer" ($0$).

Industrial Truth: The 0.5 Threshold is Almost Never Optimal

The $0.5$ cutoff assumes that false positives and false negatives carry identical business and real-world costs. In reality, errors are wildly asymmetrical:

  • Fraud Detection: A False Negative (missing a BDT 1,000,000 fraudulent wire transfer) is catastrophic. A False Positive (sending an SMS verification) costs pennies. Solution: Lower threshold to $\tau = 0.15$ or $0.20$ to maximize Recall.
  • Spam Filtering: A False Positive (sending an important CEO email to the Spam folder) is disastrous. A False Negative (one spam email in inbox) is a mild annoyance. Solution: Raise threshold to $\tau = 0.85$ or $0.90$ to protect Precision.

5. Odds, Log-Odds (Logit), and Multiplicative Coefficient Interpretation

In linear regression, a weight $w_j$ directly represents the expected additive increase in $y$ per unit increase in $x_j$. In logistic regression, because the target probability is non-linear, weights are interpreted through Odds and Odds Ratios.

Odds Formulation
$$\text{Odds} = \frac{p}{1 - p}$$
Ratio of the probability of an event occurring ($p$) to the probability of it not occurring ($1 - p$). If $p = 0.80$, $\text{Odds} = \frac{0.8}{0.2} = 4.0$ ($4:1$ odds of purchase).
Log-Odds (The Logit)
$$\ln\left(\frac{p}{1 - p}\right) = \mathbf{w}^T \mathbf{x} + b$$
The natural logarithm of odds. This reveals the core duality: Logistic Regression models a strictly linear relationship between input features and the Log-Odds of the positive class!
📐 Interpreting Learned Weights: The Odds Ratio ($e^{w_j}$)

Suppose our trained customer model learns a weight of $w_{\text{visit}} = 0.80$ for the feature $x_{\text{visit}}$ (website visits).

1. Additive effect on Log-Odds: $\Delta \text{Log-Odds} = +0.80$ per additional website visit.
2. Exponentiating yields the Odds Ratio: $\text{OR} = e^{0.80} \approx 2.225$.
Conclusion: Holding all other features constant, each additional website visit multiplies the odds of purchase by approximately 2.23 (a 123% increase in purchase odds)!

6. Loss Function: Binary Cross-Entropy (Log Loss) vs. Mean Squared Error

Why can't we train logistic regression by minimizing Mean Squared Error ($\sum (y_i - \hat{p}_i)^2$)?

The Non-Convex Local Minima Trap

When the non-linear Sigmoid function $\sigma(z)$ is inserted into a squared loss function $(y - \sigma(z))^2$, the resulting cost surface is non-convex—riddled with dozens of local minima, saddle points, and plateaus where gradient descent becomes hopelessly trapped.

To guarantee a convex bowl-shaped optimization surface with a unique global minimum, Logistic Regression is trained via Maximum Likelihood Estimation (MLE), formalized as Binary Cross-Entropy (BCE) or Log Loss:

$$J(\mathbf{w}, b) = -\frac{1}{n} \sum_{i=1}^n \left[ y_i \ln(p_i) + (1 - y_i) \ln(1 - p_i) \right]$$
Case 1: Actual Ground Truth $y_i = 1$
$$\text{Loss} = -\ln(p_i)$$
If model predicts $p = 0.99$, Loss $= -\ln(0.99) \approx 0.01$ (nearly zero). If model arrogantly predicts $p = 0.01$, Loss $= -\ln(0.01) \approx 4.60$ (approaches $\infty$). Confident wrong predictions are punished ruthlessly!
Case 2: Actual Ground Truth $y_i = 0$
$$\text{Loss} = -\ln(1 - p_i)$$
If model predicts $p = 0.01$, Loss $= -\ln(0.99) \approx 0.01$. If model erroneously predicts $p = 0.99$, Loss $= -\ln(0.01) \to \infty$.

7. Classification Performance Evaluation: Beyond Accuracy

In regression, evaluation is straightforward (MAE, RMSE, $R^2$). In classification, raw Accuracy is frequently misleading—particularly on imbalanced datasets.

7.1 The Confusion Matrix Blueprint

Every classification decision falls into one of four mutually exclusive quadrants:

Ground Truth Label Predicted Positive ($\hat{y} = 1$) Predicted Negative ($\hat{y} = 0$)
Actual Positive ($y = 1$) True Positive (TP)
Correctly caught fraud
False Negative (FN)
Type II Error (Missed fraud!)
Actual Negative ($y = 0$) False Positive (FP)
Type I Error (False alarm)
True Negative (TN)
Correctly cleared legit user
Accuracy: Overall Correctness
$$\text{Accuracy} = \frac{\text{TP} + \text{TN}}{\text{TP} + \text{TN} + \text{FP} + \text{FN}}$$
Proportion of total correct decisions. The Accuracy Trap: In a fraud dataset where 99% of transactions are legitimate, a useless dummy model that predicts "Legitimate" 100% of the time scores 99% accuracy while detecting 0 frauds!
Precision: Reliability of Positive Alarms
$$\text{Precision} = \frac{\text{TP}}{\text{TP} + \text{FP}}$$
Out of all cases labeled positive by the model, how many were genuinely positive? High precision ensures that when the system raises an alarm, it is trustworthy.
Recall (Sensitivity): Coverage of True Positives
$$\text{Recall} = \frac{\text{TP}}{\text{TP} + \text{FN}}$$
Out of all genuine positive cases in existence, what percentage did the model capture? Vital when missing positive cases carries fatal consequences (disease, security breach).
F1-Score: Harmonic Mean Balance
$$\text{F1} = 2 \cdot \frac{\text{Precision} \cdot \text{Recall}}{\text{Precision} + \text{Recall}}$$
Harmonic mean penalizing extreme imbalances between Precision and Recall. Reaches $1.0$ only when both Precision and Recall are high.
ROC-AUC: Threshold-Independent Ranking Quality

The Receiver Operating Characteristic (ROC) curve plots True Positive Rate ($\text{TPR} = \text{Recall}$) against False Positive Rate ($\text{FPR} = \frac{\text{FP}}{\text{FP} + \text{TN}}$) across all possible decision thresholds from $0.0$ to $1.0$.

$\text{AUC} = 0.50$: Random Guessing
$\text{AUC} \ge 0.85$: Strong Separability
$\text{AUC} = 1.0$: Perfect Ranking

8. Complete Scikit-Learn Python Implementation

Below is a complete, production-grade workflow modeling a synthetic imbalanced customer classification dataset (90% non-buyers, 10% buyers) with stratified partitioning, pipeline scaling, and threshold optimization.

logistic_regression_pipeline.py Python 3.10+ · Scikit-Learn 1.3+
# Step 1: Scientific & Machine Learning Imports
import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.metrics import (
    accuracy_score, precision_score, recall_score,
    f1_score, roc_auc_score, confusion_matrix, classification_report
)

# Step 2: Synthesize Imbalanced Customer Dataset (2,000 samples, 90/10 Class Ratio)
X, y = make_classification(
    n_samples=2000,
    n_features=10,
    n_informative=5,
    n_redundant=2,
    n_classes=2,
    weights=[0.90, 0.10],
    random_state=42
)

# Step 3: Stratified 70/15/15 Partitioning (Train, Validation, Test)
X_train, X_temp, y_train, y_temp = train_test_split(
    X, y, test_size=0.30, random_state=42, stratify=y
)
X_val, X_test, y_val, y_test = train_test_split(
    X_temp, y_temp, test_size=0.50, random_state=42, stratify=y_temp
)

print(f"Dataset Partitions: Train={len(X_train)}, Val={len(X_val)}, Test={len(X_test)}")

# Step 4: Construct Safe Leak-Free Preprocessing Pipeline
pipeline = make_pipeline(
    StandardScaler(),
    LogisticRegression(max_iter=1000, random_state=42)
)

# Step 5: Fit Exclusively on Training Observations
pipeline.fit(X_train, y_train)

# Step 6: Generate Continuous Probabilities on Validation Set
y_val_probs = pipeline.predict_proba(X_val)[:, 1]

# Step 7: Hyperparameter Tuning: Optimize Decision Threshold for F1-Score
thresholds = np.arange(0.10, 0.91, 0.05)
best_thresh = 0.50
best_f1 = 0.0

for t in thresholds:
    val_preds = (y_val_probs >= t).astype(int)
    score = f1_score(y_val, val_preds, zero_division=0)
    if score > best_f1:
        best_f1 = score
        best_thresh = t

print(f"Optimized Validation Threshold: {best_thresh:.2f} (Achieved F1: {best_f1:.3f})")

# Step 8: Apply Optimal Threshold to Final Unseen Test Data
y_test_probs = pipeline.predict_proba(X_test)[:, 1]
y_test_preds = (y_test_probs >= best_thresh).astype(int)

# Step 9: Quantify Final Generalization Metrics
acc = accuracy_score(y_test, y_test_preds)
prec = precision_score(y_test, y_test_preds, zero_division=0)
rec = recall_score(y_test, y_test_preds, zero_division=0)
f1 = f1_score(y_test, y_test_preds, zero_division=0)
roc_auc = roc_auc_score(y_test, y_test_probs)

print(f"\n=== FINAL TEST EVALUATION (Threshold = {best_thresh:.2f}) ===")
print(f"Accuracy  : {acc:.4f}")
print(f"Precision : {prec:.4f}")
print(f"Recall    : {rec:.4f}")
print(f"F1-Score  : {f1:.4f}")
print(f"ROC-AUC   : {roc_auc:.4f}")

# Step 10 & 11: Confusion Matrix & Classification Report
cm = confusion_matrix(y_test, y_test_preds, labels=[0, 1])
print(f"\nConfusion Matrix:\n{cm}")
print(f"\nDetailed Classification Report:\n")
print(classification_report(y_test, y_test_preds, target_names=["Non-Buyer", "Buyer"]))

9. Production Strategies for Imbalanced Datasets

When working on severe class imbalances (e.g. 1% fraud), standard logistic regression can be optimized through three critical engineering techniques:

1. Balanced Class Weighting (class_weight='balanced') Adjusts the loss function weights inversely proportional to class frequencies: $w_k = \frac{n}{K \cdot n_k}$. Heavily penalizes misclassifications of minority fraud instances, forcing the decision boundary away from the minority class.
2. Precision-Recall AUC (PR-AUC) over ROC-AUC When true negatives dominate ($99.9\%$), ROC-AUC remains deceptively high because False Positive Rate stays tiny ($\text{FPR} = \frac{\text{FP}}{\text{TN}}$). The Precision-Recall curve focuses strictly on the positive class without being inflated by overwhelming true negatives.
3. Cost-Sensitive Threshold Tuning Formulate an explicit economic cost function: $\text{Total Cost} = C_{\text{FP}} \cdot \text{FP} + C_{\text{FN}} \cdot \text{FN}$. Select the threshold $\tau^*$ that minimizes total business currency loss on the validation set.

10. Multiclass Classification: One-vs-Rest vs. Multinomial Softmax

When expanding beyond binary choices to $K > 2$ classes (e.g. classifying user sentiment into Positive, Neutral, or Negative), Logistic Regression utilizes two primary strategies:

One-vs-Rest (OvR / One-vs-All)

Trains $K$ separate binary logistic regression models. Model $k$ separates class $k$ from all other remaining classes. At inference time, the class yielding the highest probability is selected: $\hat{y} = \arg\max_k P(y = k)$.

Multinomial Logistic Regression (Softmax)

Models all $K$ classes simultaneously by normalizing linear scores across classes via the Softmax function:

$$P(y = k \mid \mathbf{x}) = \frac{e^{z_k}}{\sum_{j=1}^K e^{z_j}}$$

Guarantees that $\sum_{k=1}^K P(y = k \mid \mathbf{x}) = 1.0$. This is the standard output layer architecture of modern Deep Learning classification networks.

11. Five Core Assumptions & Architectural Limitations

1. Linearity in the Log-Odds The model assumes that the continuous features have a linear relationship with the logit $\ln(p / (1-p))$. Non-linear relationships require polynomial expansion or spline binning.
2. Linear Decision Boundaries In original feature space, Logistic Regression can only produce a linear separating hyperplane ($\mathbf{w}^T \mathbf{x} + b = 0$). Concentric rings or XOR logic gates cannot be separated without feature transformations.
3. The Perfect Separation Hazard (Quasi-Complete Separation) If a feature perfectly separates the classes (e.g., all fraudulent transactions have feature $x > 5$ and all legit transactions have $x \le 5$), the optimal weight $w \to +\infty$. Standard OLS/MLE diverges without $L_2$ Regularization (Ridge penalty).
4. Absence of Severe Multicollinearity Collinear features inflate weight variance, rendering Odds Ratios ($e^{w_j}$) unreliable for causal or feature importance interpretation.
5. Sample Independence Observations must be independent. Grouped records from the same user over time violate this assumption (requiring mixed-effects or GEE modeling).
Interactive Simulator

Logistic Regression Laboratory

Experiment with Sigmoid probability mapping, tune decision thresholds, and analyze Confusion Matrix metrics live

0.00
Controls the pre-activation input to the Sigmoid function.
0.50
Cutoff dividing Negative Class (0) from Positive Class (1).
Sigmoid Equation: $\sigma(z) = \frac{1}{1 + e^{-z}}$
Sigmoid Curve Threshold Line ($\tau$) Current Operating Point
Probability $\hat{p}$ 50.0%
Calculated Odds 1.00 : 1
Log-Odds (Logit) 0.00
Class Prediction Positive (1)

12. Summary & Key Takeaways

Sigmoid Squashing Converts real-valued linear scores $z \in (-\infty, \infty)$ strictly into bounded probability estimates $p \in (0, 1)$.
Multiplicative Odds Ratios Weights represent linear changes in Log-Odds; exponentiating weights ($e^{w_j}$) reveals the factor by which event odds multiply.
Convex Log Loss Optimization Binary Cross-Entropy creates a smooth convex landscape that guarantees gradient descent converges without trapping in local minima.
Strategic Threshold Tuning The default 0.5 threshold must be tailored using Validation PR curves to reflect asymmetric business costs between False Positives and False Negatives.
Next Lesson · Non-Linear Trees

Lesson 15.16: Decision Trees: Learning from Data

While linear classifiers carve flat boundaries, Decision Trees create hierarchical axis-aligned orthogonal decision boundaries. Next, we explore recursive binary splitting, Gini Impurity vs. Shannon Entropy, information gain, and tree pruning strategies.

Proceed to Next Lesson