How Machines Learn Guide 2 of 6 · tap to switch
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.
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.
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.
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.
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:
2. Sigmoid (inverse logit): Solving for the probability yields the logistic sigmoid:
Every 1-unit increase in feature multiplies the odds by (the odds ratio, widely reported in medical and social science papers).
3. Maximum Likelihood Estimation & Binary Cross-Entropy (Log-Loss): Treating each label as , maximizing the log-likelihood across independent examples is mathematically identical to minimizing average Log-Loss:
4. No closed-form solution, yet a single global bowl: Setting the gradient produces a non-linear system with no Normal Equation shortcut. However, the Hessian (with diagonal weights ) is positive semi-definite everywhere, making 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 ; adding L2 regularization () keeps weights finite and probabilities calibrated.
See how clean this is in PythonOptional Code
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.
Before deploying logistic regression on a real yes/no problem, run four practical checks:
- 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.
- 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.
- 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).
- 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.
Quick Intuition Check
Four quick real-world scenarios. No scores, just test your intuition.
Why does linear regression fail when you fit it directly to 0 (Safe) and 1 (Fraud) card outcomes?
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?
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?
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.
Common Questions
Why is logistic regression called regression if it is used for classification?
What does the sigmoid function do in logistic regression?
Why does logistic regression use log-loss instead of Mean Squared Error?
Should the decision threshold in logistic regression always be 0.5?
When does logistic regression fail?
Related Visual Guides
Precision, Recall, F1 Score & Imbalanced Data
Why 99% accuracy can hide a totally broken model, how Precision, Recall, F1, and PR curves expose the truth, and what fixes actually work.
Activation Functions (ReLU, Sigmoid & GELU)
Why every neural layer needs a non-linear bend, how ReLU cured vanishing gradients, and why modern LLMs love GELU.
Support Vector Machines (SVM)
Carve the widest possible safety margin between classes, ignore interior clutter, and curve boundaries effortlessly using the Kernel Trick.
Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference
Cite this guide in a paper, thesis, or course (BibTeX & APA)
@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}
} Irshad, M. A. (2026). Logistic Regression: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/logistic-regression/