Machine Learning Slides 📂 Introduction · 3 of 17 49 min read

Logistic Regression Explained

A visual, beginner-friendly guide to Logistic Regression built around a real oncology case study. Learn why linear regression fails at classification, the sigmoid function, log-odds intuition, binary cross-entropy cost, gradient descent, decision boundaries, confusion matrices, precision/recall/F1, ROC-AUC, regularisation (L1/L2), multiclass softmax extensions, and six golden rules every practitioner must follow.

🎯

Logistic Regression

The workhorse classifier of applied ML — sigmoid intuition, log-odds math, the log-loss cost function, confusion matrices, ROC-AUC and the pitfalls that trap beginners every time.
Sigmoid & Log-Odds Log Loss Confusion Matrix ROC-AUC

Press Next → or use ← → arrow keys

Section 01

What is Logistic Regression?

Dr. Sharma, a Bengaluru oncologist, needs a second opinion — with a confidence score
Every biopsy report gives Dr. Sharma the same measurements: tumour size, cell uniformity, clump thickness. A binary answer ("benign" or "malignant") isn't enough — she needs a probability. "87% likely malignant" drives very different clinical action than "51% likely malignant."

Logistic Regression is the classifier that outputs exactly that — a probability between 0 and 1, then applies a threshold to turn it into a decision. Despite the name, it's classification, not regression.
💡
The Working Definition

Logistic Regression is a supervised algorithm for binary classification that predicts the probability an observation belongs to Class 1, then applies a threshold (default 0.5) to produce a label.

0 → 1Bounded probability output
0.5Default decision threshold
6Core assumptions
#1Baseline classifier in ML
Section 02

Why Linear Regression Fails at Classification

Feeding a linear model a 0/1 target technically runs — but the outputs are nonsense for a classifier.

📉
Unbounded Output
predictions escape [0,1]
A linear model can output −0.34 or 1.72 — meaningless as a probability. There is no maths for "−34% cancer."
✂️
No Natural Threshold
where does class 1 start?
What does "0.73 kg of malignant" mean? Linear outputs have no principled cut-point separating the two classes.
🎯
Outlier Fragility
one extreme skews the line
A single extreme feature value tilts the whole regression line, misclassifying dozens of otherwise clean samples.
🛠️
The Fix — Squash The Output Into [0, 1]

Logistic Regression takes the same linear score and passes it through the sigmoid function. Every real number in, a valid probability out. Meet it on the next slide.

Section 03

The Sigmoid — Any Number → A Probability

−6 −2 0 +2 +6 z (linear score) 1.0 0.5 0.0 threshold = 0.5 ← predict Class 0 predict Class 1 → σ(z) = 1 / (1 + e⁻ᶻ)
🌊
Four Facts To Memorise

σ(0) = 0.5 (pure uncertainty). σ(+∞) → 1. σ(−∞) → 0. The curve is symmetric around zero. Any linear score enters; a valid probability comes out.

Section 04

The 4-Step Pipeline

📐 Linear Score z = β₀ + β·x 🌊 Sigmoid p̂ = σ(z) ✂️ Threshold ŷ = 1 if p̂ ≥ 0.5 🏷️ Report label + confidence
Step 1 — Logit
z = β₀ + β₁x₁ + β₂x₂ + … + βₙxₙ
Identical to linear regression's linear combination — a weighted sum of features.
Step 2 — Sigmoid
p̂ = σ(z) = 1 / (1 + e⁻ᶻ)
Squashes any real number into (0, 1) — the estimated probability of Class 1.
🎯
Always Report Both

"Malignant" is a decision. "87% confident this is malignant" is a usable decision. Send both to the human downstream.

Section 05

Log-Odds — Where The Name Comes From

Invert the sigmoid algebraically and something beautiful appears: the log-odds of the outcome are a linear function of the features.

The Logit Equation
ln(p̂ / (1 − p̂)) = β₀ + β₁x₁ + … + βₙxₙ
Left side is the log-odds. Right side is linear. That's why it's called logistic regression.
Coefficient Interpretation
e^βⱼ = odds ratio per unit of xⱼ
If β = 0.8, then e^0.8 ≈ 2.23 — each extra unit multiplies the odds of Class 1 by 2.23×.
ProbabilityOdds p / (1 − p)Log-Odds ln(odds)Meaning
0.100.111−2.20Strongly Class 0
0.250.333−1.10Likely Class 0
0.501.0000.00Coin flip
0.753.000+1.10Likely Class 1
0.909.000+2.20Strongly Class 1
🧮
Why Log-Odds Instead of Probability?

Log-odds are unbounded (−∞ to +∞) — the natural output space of a linear model. The sigmoid is just a translation layer between the linear world and the probability world.

Section 06

The Cost Function — Binary Cross-Entropy

Actual = 1 (positive) loss = −log(p̂) · penalises low confidence predicted probability p̂ → loss → confident wrong → huge loss Actual = 0 (negative) loss = −log(1 − p̂) · penalises high confidence predicted probability p̂ → loss → confident wrong → huge loss
Single-sample loss
L = −[ y·log(p̂) + (1−y)·log(1−p̂) ]
Two branches — one activates when y=1, the other when y=0.
Batch cost
J(β) = −(1/n) Σ [ yᵢ·log(p̂ᵢ) + (1−yᵢ)·log(1−p̂ᵢ) ]
Convex — gradient descent is guaranteed to find the global minimum.
📉
The Asymmetry Is The Feature, Not A Bug

Log loss explodes toward infinity for confidently-wrong predictions. That's what forces the model to output well-calibrated probabilities rather than lazy 50/50 guesses.

Section 07

Gradient Descent — One Beautiful Update Rule

Gradient (per coefficient)
∂J / ∂βⱼ = (1/n) Σ (p̂ᵢ − yᵢ) · xᵢⱼ
Prediction error times feature value, averaged. Simpler than it looks.
Weight Update
βⱼ ← βⱼ − α · ∂J/∂βⱼ
Nudge each weight in the direction that reduces loss. Repeat until convergence.

A single-iteration walk-through — 4 samples, initial β = 0, learning rate α = 0.1:

Size (x)Label (y)z = 0p̂ = σ(0)Error (p̂ − y)
2000.5+0.5
3000.5+0.5
5100.5−0.5
7100.5−0.5
🎯
The Update — β₁ Becomes Positive

∂J/∂β₁ = (0.5·2 + 0.5·3 − 0.5·5 − 0.5·7) / 4 = −0.875. β₁ ← 0 − 0.1·(−0.875) = +0.0875. After just one step, larger tumours already receive higher malignancy probability. Convex loss → guaranteed global minimum. ✅

Section 08

The Decision Boundary — A Straight Line in 2D

Tumour Size (mm) → Cell Uniformity → Benign (p̂ < 0.5) Malignant (p̂ ≥ 0.5) ← boundary: β₀ + β·x = 0
📏
The Boundary Is Always Linear

A line in 2D, a plane in 3D, a hyperplane in n-D. If your classes are non-linearly separable (one wrapped around the other), plain logistic regression will struggle — reach for polynomial features, kernels or tree-based models.

Section 09

Confusion Matrix — The Truth Table

Predicted Benign Malignant Actual Benign Malignant 57 TN — correct benign 5 FP — unnecessary biopsy 3 FN — MISSED CANCER 35 TP — caught cancer 100 test samples · 38 malignant · 62 benign
💔
Not All Errors Cost The Same

A False Positive means an unnecessary biopsy — inconvenient. A False Negative means a missed cancer — potentially fatal. In medicine you tune the threshold to minimise FN even at the cost of extra FP.

Section 09 · Metrics

Accuracy · Precision · Recall · F1

Accuracy
(TP + TN) / Total = 92%
Only trustworthy when classes are balanced. Fails silently on imbalanced data.
Precision
TP / (TP + FP) = 35/40 = 87.5%
"When I predict positive, how often am I right?" Use when false alarms are expensive.
Recall (Sensitivity)
TP / (TP + FN) = 35/38 = 92.1%
"Of all real positives, how many did I catch?" Use when missing a case is expensive.
F1 Score
2·P·R / (P + R) ≈ 89.7%
Harmonic mean — one score balancing precision and recall on imbalanced data.
🎚️
Threshold Tuning — A Domain Decision

Drop Dr. Sharma's threshold from 0.5 → 0.3 and recall jumps from 92% to 97% (fewer missed cancers). The trade-off: precision falls to 74% (more benign biopsies). In oncology, that trade is worth it. In spam-filtering, the reverse.

Section 10

ROC Curve & AUC — Threshold-Independent Quality

0 1 0 1 False Positive Rate → True Positive Rate → random (AUC=0.5) perfect AUC = 0.97
AUC RangeVerdictWhat It Means
0.50RandomModel has no discriminative power
0.70 – 0.80AcceptableUseful for triage / ranking
0.80 – 0.90GoodProduction-ready in most domains
0.90 – 1.00ExcellentCheck for data leakage before celebrating
📊
Threshold-Free Model Comparison

AUC = the probability the model ranks a random positive higher than a random negative. It's threshold-independent — perfect for comparing model versions. For very imbalanced data (fraud < 0.1%), use PR-AUC instead.

Section 11

Regularisation & Multiclass Extensions

🎚️
L2 — Ridge
penalty: λ · Σβⱼ²
Shrinks all weights toward zero but never to zero. Best when most features contribute. sklearn default.
✂️
L1 — Lasso
penalty: λ · Σ|βⱼ|
Drives useless weights to exactly zero — automatic feature selection. Best with many irrelevant features.
🔗
ElasticNet
L1 + L2 combined
Sparsity from L1, stability from L2. Best with many correlated features.
🎯
More Than Two Classes — Two Strategies

One-vs-Rest (OvR) trains K binary classifiers, one per class — simple & fast. Softmax (Multinomial) trains one model with K outputs; the softmax function turns scores into a proper probability distribution that sums to 1. Softmax is the industry default and the foundation of neural-network classifiers.

Softmax
P(class k) = e^zₖ / Σⱼ e^zⱼ
Every class score becomes a probability. All K probabilities sum to exactly 1.
sklearn — Regularisation
C = 1 / λ (default C = 1.0, L2)
Small C = strong regularisation. Tune via cross-validation.
Section 12

Implementation — Scratch vs Scikit-learn

# ── FROM SCRATCH · the whole model in ~20 lines ──
import numpy as np

def sigmoid(z):
    return 1 / (1 + np.exp(-z))

def train_logistic(X, y, lr=0.1, epochs=1000):
    n, p = X.shape
    beta = np.zeros(p + 1)
    X_b  = np.column_stack([np.ones(n), X])
    for _ in range(epochs):
        p_hat = sigmoid(X_b @ beta)
        grad  = (1/n) * (X_b.T @ (p_hat - y))
        beta -= lr * grad
    return beta

# ── PRODUCTION · scikit-learn one-liner ─────────
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler

X_train = StandardScaler().fit_transform(X_train)   # ALWAYS scale!
model = LogisticRegression(C=1.0, max_iter=1000)
model.fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]           # Class 1 probability
⚠️
Fit The Scaler On TRAINING Data Only

scaler.fit_transform(X_train) then scaler.transform(X_test) — never re-fit. Fitting on the full dataset leaks test statistics into training and inflates every metric.

Section 13

Common Pitfalls — What Bites Beginners

📏
Forgetting Scaling
Features on wildly different scales (age vs income) cause slow, biased convergence. Always StandardScaler.
📊
Accuracy On Imbalanced Data
99% "not fraud" data → predict "no" always → 99% accuracy, zero criminals caught. Use F1, PR-AUC or recall.
🎚️
Default 0.5 Everywhere
0.5 maximises accuracy — not business value. Tune the threshold per domain (medicine ↓, spam ↑).
🚫
Perfect Separation
If one feature perfectly separates classes, coefficients diverge to ±∞. Add regularisation or drop the feature.
🔗
Multicollinearity
Highly correlated features destabilise coefficients & break interpretability. Drop, combine, or use L2.
🕸️
Non-Linear Classes
Concentric rings, XOR patterns — no straight boundary works. Add polynomial features, or switch to trees / SVM.
Section 14 · Part 1

Golden Rules — 1 to 3

🎯 LOGISTIC REGRESSION DISCIPLINE · RULES 1–3
1
Always scale your features. Logistic regression is magnitude-sensitive. Use StandardScaler. Fit on training only, transform test — anything else is data leakage.
2
Never trust accuracy alone on imbalanced data. Always pair it with Precision, Recall, F1 — and PR-AUC when the positive class is rare (fraud < 1%).
3
Tune the decision threshold to your domain. Cancer screening: drop it to catch every case. Spam filter: raise it so the CEO's email doesn't get quarantined. Plot the Precision–Recall curve and pick the operating point deliberately.
Section 14 · Part 2

Golden Rules — 4 to 6

🎯 LOGISTIC REGRESSION DISCIPLINE · RULES 4–6
4
Use ROC-AUC to compare model versions. Threshold-independent, works well for moderately imbalanced data. Prefer PR-AUC once positives fall below ~1%.
5
Regularise by default. sklearn's C=1.0 (L2) is a safe start. Try L1 with many noisy features. Always tune C via cross-validation.
6
Watch for perfect separation. Signs: huge coefficients, ∞ confidence intervals, convergence warnings. Fix: regularisation or dropping the separating feature.
📈
Ship The Baseline First

A properly tuned logistic-regression baseline is often the model in production for years. Fancy techniques earn deployment only when they beat this baseline meaningfully.

FINAL

Logistic Regression — Probabilities, Not Guesses

σ(z)Sigmoid squashes to [0, 1]
4Pipeline steps
LogConvex loss · global minimum
4Classification metrics
6Golden rules
0.97Dr. Sharma's ROC-AUC
🎯
The Foundation Is Set

You now understand the sigmoid, log-odds, log-loss, gradient descent, decision boundaries, confusion matrices and ROC-AUC. Every classifier that follows — SVMs, random forests, gradient boosting, even the softmax layer of a neural network — extends the ideas you just learned.

📚
Where To Go Next

Study softmax & multiclass classification, then Naive Bayes for comparison, then jump to SVMs and tree-based classifiers. Practice on Kaggle's Titanic and Breast Cancer datasets — exactly Dr. Sharma's problem.

🎯 End of tutorial · Press to review, or click Restart