SeeingML
How Machines Learn Guide 2 of 6 · tap to switch
✦ Interactive Visual Guide 9 min · 5 hands-on labs · Beginner friendly

Logistic Regression

How a machine turns clues into clean 0% to 100% probabilities and makes yes/no decisions, from spam filters to bank fraud alerts.

Logistic regression is the classic machine learning tool for answering yes-or-no questions with a probability: Is this email spam? Does this scan need a specialist? Is this late-night card payment fraud?

Think about that text from your bank: “Did you just spend £460 at an electronics store abroad?” Unlike house prices (where linear regression predicts any pound figure), fraud only has two real outcomes: Safe (0) or Fraud (1).

You might wonder why we do not just reuse a straight line from linear regression. Try it below. Start on Straight Line, click + Add £2,200 Luxury Wire Fraud to watch one huge confirmed fraud break the line, then switch to S-Curve to see the fix.

Interactive Lab 1: Why a Straight Line Breaks on Yes/No
Safe (0)Fraud (1)Mistake at 50% cut
Hover or click any dot to inspect its score
Impossible (> 100% chance)Impossible (< 0% chance)Predicted Score / Risk0%50%100%£0£200£400£600£800Card Transaction Amount (£)50% cut: £349
Impossible outputs: 3Frauds caught: 6/7
Look at the shaded red danger bands: linear regression predicts -3% fraud chance on an £18 coffee and 130% on an £850 purchase (both impossible!). Next, click "+ Add £2,200 Luxury Wire Fraud" to see what one extreme fraud does to the line.

A straight line fails in two fatal ways on yes/no data. First, it shoots past 100% and dips below 0%, producing nonsense probabilities like -3% chance of fraud on an £18 morning coffee and 130% chance of fraud on larger bills. Second, a single huge £2,200 fraud forces the straight ruler to flatten out so it does not overshoot 100%, dragging its 50% cutoff so far right that real £380 frauds slip through unblocked. Meanwhile, the sigmoid S-curve levels off smoothly near 100% and barely flinches.

Logistic regression fixes both problems with one elegant trick: it takes the exact same weighted score, then feeds it through an S-shaped sigmoid curve that smoothly squeezes every output between 0% and 100%.


Turning probabilities into real decisions

A probability by itself does not block a stolen card. Your bank still has to decide: how suspicious is suspicious enough to freeze the payment and text the customer?

That cutoff is the decision threshold. By default, models use 50%, but in real life you almost never leave it there. Grab the amber threshold bar on the chart below and drag it up and down to feel the real tug-of-war between missed frauds (called false negatives) and false alarms on innocent shoppers (called false positives). You can also experiment with the curve’s midpoint and steepness underneath to see how the learned probability curve differs from your alarm cutoff.

Interactive Lab 2: Decision Threshold vs. Learned S-Curve
Safe (0)Fraud (1)Amber ring = mistake
Drag the amber alarm bar up or down on the chart
APPROVE AS SAFESEND FRAUD ALERTPredicted Fraud Chance0%25%50%75%100%£0£200£400£600£800Card Transaction Amount (£)↕ Alarm at 50%
Frauds Caught
6
Missed Frauds (FN)
1
False Alarms (FP)
1
Safe Approved
6
1. Your Alarm Cutoff (Decision Threshold)
Chosen by the bank to balance missed frauds vs. false alarms (never changes the curve).
50% (around £300)
2. Model's Curve Shape (Normally Learned Automatically)
Explore how shifting the midpoint or sharpening the slope changes predicted probabilities.
£300
Lower spend (£100)Higher spend (£650)
Steep S-curve
Gentle slopeSharp cliff
At a 50% alarm threshold (curve shape: steep s-curve), transactions above £300 trigger an alert: 6 frauds caught, 1 missed fraud (false negatives), and 1 false alarm (false positives).

Notice the clean separation of responsibilities:

  • The S-curve (learned from past transactions) estimates honest probabilities.
  • The decision threshold (chosen by humans based on real-world costs) decides where to pull the alarm: lower it to prevent dangerous missed frauds (false negatives), or raise it to avoid annoying innocent shoppers with false alarms (false positives).

How logistic regression scores its mistakes (Log-Loss)

In linear regression, we judged a line by squaring every miss (called Mean Squared Error). On yes/no probabilities, squared error is far too polite. If a payment is real fraud and your model confidently insists there is only a 1% chance of fraud, squared error barely hands out a mild penalty of 0.98.

Logistic regression uses Log-Loss (also called binary cross-entropy) instead. Log-Loss stays tiny when the model is confident and right, stays modest when the model admits it is unsure (50/50), and shoots sharply skyward whenever the model is dead certain and dead wrong. Predicting a 1% chance on a real fraud incurs a harsh Log-Loss penalty of 4.61, and that penalty climbs toward infinity as a wrong prediction gets closer to 0%.

Slide the predicted probability on the left to feel that penalty spike, then hit Let It Learn on the right to watch the S-curve tighten itself automatically by stepping down Log-Loss.

Interactive Lab 3: Log-Loss Penalty & Watching It Learn
Left: inspect 1 mistake | Right: watch all 14 sales train
1. Penalty for One PredictionLog-Loss: 0.16
Log-LossSquared Error
Penalty Score012340%50%100%Model's Predicted Fraud Chance
85%
Confident and right! Predicted 85% fraud when the transaction was Fraud, so Log-Loss stays tiny (0.16). Drag the slider toward 5% to feel the sharp penalty spike.
2. Shrinking Log-Loss on All 14 SalesStep 0 | Loss 0.51
Safe (0)Fraud (1)
Goal: lowest average Log-Loss
Fraud Chance0%50%100%£0£300£600£900Transaction Amount (£)
Starting from a poor flat guess (average Log-Loss 0.51). Click "Take 1 Step" or "Let It Learn" to watch Log-Loss pull the S-curve into place.

Because Log-Loss punishes overconfident blunders so fiercely, logistic regression naturally learns well-calibrated probabilities: when it says a purchase has an 80% chance of being fraud, roughly 8 out of 10 similar transactions really are fraud.


Using multiple clues at once: the 2D decision boundary

No real bank judges fraud from price alone. A £520 furniture purchase 15 km from your home looks completely normal; a £480 phone purchase 360 km away screams stolen card.

Just like multiple linear regression, logistic regression gives each clue its own weight (one for price, one for distance from home) and passes their sum through the sigmoid curve. Where the combined probability hits your alarm threshold, you get a clean decision boundary slicing the map into a Safe Zone and a Fraud Alert Zone.

Click anywhere on the map below to drop new Fraud or Safe transactions and watch the dividing line adapt, or slide the threshold to push the boundary back and forth.

Interactive Lab 4: Two Clues at Once (2D Decision Boundary)
Safe (0)Fraud (1)Amber ring = mistakeDecision boundary
Click anywhere on the map to add a point
Distance from home (km)0 km100 km200 km300 km400 km500 km£0£200£400£600£800£1000Transaction Amount (£)SAFE ZONEFRAUD ALERT ZONE
50%
Accuracy: 100%Mistakes: 0
Combining Price and Distance lets one straight dividing line reach 100% accuracy at a 50% threshold with zero amber mistake rings (every point sits on the right side of the fence). Click anywhere on the map to drop new Fraud or Safe examples, or slide the threshold below to push the line.
See the exact math, log-odds, MLE & statistical assumptionsThesis / Reference

1. Log-odds (the logit link function): Logistic regression models the natural log of the odds as a linear function of the inputs:

ln⁡ ⁣(p1−p)=z=b+w1x1+w2x2+⋯+wpxp=x⊤β\ln\!\left(\frac{p}{1 - p}\right) = z = b + w_1 x_1 + w_2 x_2 + \dots + w_p x_p = \mathbf{x}^\top \boldsymbol{\beta}

2. Sigmoid (inverse logit): Solving for the probability p=P(Y=1∣x)p = P(Y = 1 \mid \mathbf{x}) yields the logistic sigmoid:

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

Every 1-unit increase in feature xjx_j multiplies the odds p1−p\frac{p}{1-p} by ewje^{w_j} (the odds ratio, widely reported in medical and social science papers).

3. Maximum Likelihood Estimation & Binary Cross-Entropy (Log-Loss): Treating each label as Yi∼Bernoulli(p^i)Y_i \sim \text{Bernoulli}(\hat{p}_i), maximizing the log-likelihood across independent examples is mathematically identical to minimizing average Log-Loss:

L(β)=−1n∑i=1n[ yiln⁡p^i+(1−yi)ln⁡(1−p^i) ]\mathcal{L}(\boldsymbol{\beta}) = -\frac{1}{n} \sum_{i=1}^{n} \left[\, y_i \ln \hat{p}_i + (1 - y_i) \ln(1 - \hat{p}_i) \,\right]

4. No closed-form solution, yet a single global bowl: Setting the gradient ∇βL=1nX⊤(p^−y)=0\nabla_{\boldsymbol{\beta}}\mathcal{L} = \frac{1}{n}\mathbf{X}^\top(\hat{\mathbf{p}} - \mathbf{y}) = \mathbf{0} produces a non-linear system with no Normal Equation shortcut. However, the Hessian H=1nX⊤WX\mathbf{H} = \frac{1}{n}\mathbf{X}^\top \mathbf{W} \mathbf{X} (with diagonal weights Wii=p^i(1−p^i)>0W_{ii} = \hat{p}_i(1-\hat{p}_i) > 0) is positive semi-definite everywhere, making L\mathcal{L} convex. Gradient descent, L-BFGS, or Newton-Raphson (IRLS) reliably find the global optimum.

5. Classical assumptions & complete separation: Logistic regression does not require normally distributed features or equal variance across groups. It does assume (1) independent observations, (2) linearity in the log-odds, (3) absence of severe multicollinearity, and (4) sufficient sample size per predictor. Under complete or quasi-complete separation (Albert & Anderson, 1984), where a plane separates the classes with zero overlap, unregularized weights diverge to ±∞\pm\infty; adding L2 regularization (λ∥w∥22\lambda\|\mathbf{w}\|_2^2) keeps weights finite and probabilities calibrated.

See how clean this is in PythonOptional Code
python
import numpy as np
from sklearn.linear_model import LogisticRegression

# Features: [Amount (£), Distance from home (km)]
X = np.array([
  [45, 5], [110, 18], [220, 12], [520, 15], [160, 210],
  [480, 360], [640, 260], [790, 140], [920, 420], [310, 450],
])
y = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1])

model = LogisticRegression()
model.fit(X, y)

# Predict probability for a £450 purchase 300 km from home
prob = model.predict_proba([[450, 300]])[0, 1]
threshold = 0.35  # stricter bank fraud cutoff
alert = prob >= threshold
print(f"Fraud probability: {prob:.1%} | Alert triggered: {alert}")

Where logistic regression breaks (and how one clue saves it)

Because logistic regression combines clues with a weighted sum, its decision boundary is always straight (a straight line in 2D, or a flat sheet in 3D). That simplicity makes it fast, easy to interpret, and hard to overfit (memorizing noisy quirks in past examples instead of real patterns). The catch arrives whenever the true pattern can no longer be split by one straight fence (meaning it is not linearly separable).

Consider card-testing fraud. Scammers who steal a card number often run two very different transactions: a tiny £4 to £15 probe to check if the card works, followed by a huge £700+ cash-out. Meanwhile, your normal everyday spending sits right in the middle (£120 to £380).

Inspect 1. Raw Amount (Breaks) below, then switch to 2. Distance From Usual Spend (Fixed!) to watch a simple feature transform (building a helpful new clue column, here how far a purchase strays from your usual £240 spend) turn a failing straight-line model into a clean separator.

Interactive Lab 5: When a Straight Boundary Fails (and How One Clue Saves It)
Safe (0)Fraud (1)Amber ring = mistakeStraight boundary
Hover or click any dot to trace how it moves
Time of Purchase6 PM8 PM10 PM12 AM2 AM£0£200£400£600£800£1000Raw Transaction Amount (£)Tiny probesNormal spendingHuge cash-out spikes
Straight-boundary accuracy: 65%Mistakes: 7 of 20
Stuck at 65% accuracy (7 amber-ringed mistakes)! Fraud hides on BOTH ends (tiny £4 card-testing probes on the left AND huge £800 cash-outs on the right), with safe everyday spending sandwiched in the middle. No single straight fence can slice out the middle. Click "2. Distance From Usual Spend (Fixed!)" to see the feature transform.

Before deploying logistic regression on a real yes/no problem, run four practical checks:

  1. Can one straight fence separate the classes? If fraud examples wrap around or sit on both sides of safe ones, either build a domain-smart clue (like distance from normal spend) or switch to a model that can draw curved boundaries, such as decision trees, random forests, or neural networks.
  2. Did you pick a real-world threshold? Never blindly stick with 50% when missed frauds (false negatives) and false alarms on innocent shoppers (false positives) carry wildly different costs.
  3. Are the classes heavily imbalanced? If 99% of payments are Safe, plain accuracy can fool you (guessing “Safe” every time scores 99% while catching zero fraud). Look closely at how many real frauds you caught, how many alerts were real alarms, and whether predicted probabilities match reality (for example, checking whether “80% risk” alarms really turn out to be fraud about 8 out of 10 times; we explore this deeply in our Imbalanced Data guide).
  4. Is a gentle weight-shrinking penalty turned on? If a clue separates your past examples too cleanly, plain logistic regression can crank its weights to extremes and grow overconfident. Turning on a gentle weight-shrinking penalty (called regularization) keeps weights sensible so predicted probabilities stay realistic on brand-new transactions.
✓ Self-Check

Quick Intuition Check

Four quick real-world scenarios. No scores, just test your intuition.

1

Why does linear regression fail when you fit it directly to 0 (Safe) and 1 (Fraud) card outcomes?

Pick an option first, or peek anytime
2

A hospital uses logistic regression to flag patients who need a follow-up scan. Missing a sick patient is far worse than doing an extra check. How should they adjust the decision threshold?

Pick an option first, or peek anytime
3

A fraud model predicts only a 1% chance of fraud on a transaction that turns out to be real fraud. Why does Log-Loss react so strongly?

Pick an option first, or peek anytime
4

If fraud occurs at both very tiny amounts (£5) and very large amounts (£900) while normal spending sits in the middle (£200), a plain logistic regression model using raw amount alone can separate all three regions cleanly.

Pick an option first, or peek anytime
Quick Reference

Common Questions

Why is logistic regression called regression if it is used for classification?
Under the hood, logistic regression still computes a linear weighted sum of inputs (the log-odds), just like linear regression. It then squeezes that continuous score through an S-shaped sigmoid function to output a probability between 0 and 1, which you threshold into a yes/no class.
What does the sigmoid function do in logistic regression?
The sigmoid function converts any raw number from negative infinity to positive infinity into a smooth probability between 0% and 100%. Large negative scores squeeze near 0, zero maps to exactly 50%, and large positive scores squeeze near 1.
Why does logistic regression use log-loss instead of Mean Squared Error?
Log-loss (binary cross-entropy) penalizes confident wrong predictions exponentially and creates a smooth single-bowl (convex) loss surface with one global minimum. Mean Squared Error paired with a sigmoid produces flat plateaus and local valleys that stall learning.
Should the decision threshold in logistic regression always be 0.5?
No. A 50% threshold treats false alarms and missed detections as equally costly. In cancer screening or bank fraud detection, missing a real case is far worse than an extra check, so teams often lower the threshold to 0.2 or 0.3.
When does logistic regression fail?
Plain logistic regression can only draw a straight line (or flat hyperplane) between classes. It fails when one class sits inside or on both sides of another, unless you engineer non-linear features or switch to trees or neural networks.

Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference

https://seeingml.com/learn/logistic-regression/ Open GitHub issue Suggest an edit
Cite this guide in a paper, thesis, or course (BibTeX & APA)
BibTeX
@misc{irshad2026logisticregression,
  author       = {Irshad, Muhammad Aashir},
  title        = {Logistic Regression: Interactive Visual Guide},
  howpublished = {SeeingML},
  year         = {2026},
  month        = {dec},
  url          = {https://seeingml.com/learn/logistic-regression/},
  note         = {Interactive visual guide}
}
APA

Irshad, M. A. (2026). Logistic Regression: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/logistic-regression/