Skip to content

MLDay 12 of 50Supervised and Unsupervised Learning

Logistic Regression

Your bank blocks every card payment over $500, so fraudsters charge $480 instead.

6 min read

Your bank blocks every card payment over $500, so fraudsters charge $480 instead. One rule gives a hard yes or no from one signal. You want a model that weighs several signals and says how likely a payment is fraud.

The idea

Logistic regression is a classifier: a model that predicts a category (fraud or legit) instead of a number. It works in two steps.

  1. Score. Add up weighted features plus a bias, exactly like linear regression. The score zz can be any number, like −7 or +12.
  2. Squash. The sigmoid, an S-shaped curve, turns the score into a probability pp between 0 and 1.

Why not use the straight line alone? On 2,000 payments labelled 0 (legit) or 1 (fraud), a line predicts −0.03 for a $5 coffee and +1.43 for an $800 sofa. Neither is a chance of anything.

Training picks the weights that make log loss small. Log loss is a penalty that grows fast when the model is confident and wrong. The points where p=0.5p = 0.5 form the decision boundary: fraud on one side, legit on the other.

A tiny example

Take a made-up scorecard: one point per $100, one point per 10 km from home, then minus 5.

Payment Amount Distance Score zz pp (fraud)
A $100 10 km 1 + 1 − 5 = −3 0.05
B $300 20 km 3 + 2 − 5 = 0 0.50
C $500 30 km 5 + 3 − 5 = +3 0.95

A is probably legit, B is a coin flip and C is probably fraud. B sits exactly on the decision boundary.

The formula

The sigmoid turns a score into a probability.

p=σ(z)=11+e−zp = \sigma(z) = \frac{1}{1 + e^{-z}}
Symbol Meaning
zz the score: w1x1+w2x2+bw_1 x_1 + w_2 x_2 + b (weights times features, plus the bias)
σ\sigma the sigmoid function
ee Euler's number, about 2.718
pp the predicted chance of class 1 (fraud)

Worked, payment C: z=3z = 3 gives p=11+e−3=11+0.050≈0.95p = \frac{1}{1 + e^{-3}} = \frac{1}{1 + 0.050} \approx 0.95.

Log loss scores one prediction against the true label. It's the negative log of the chance given to the right answer.

L=−[ yln⁡p+(1−y)ln⁡(1−p) ]L = -\left[\,y \ln p + (1 - y) \ln(1 - p)\,\right]
Symbol Meaning
LL the loss for one row; 0 is perfect, higher is worse
yy the true label: 1 for fraud, 0 for legit
pp the predicted chance of fraud
ln⁡\ln the natural log

Worked: C really is fraud (y=1y = 1), so L=−ln⁡0.95≈0.05L = -\ln 0.95 \approx 0.05. Now say A was fraud too, a thief testing a stolen card. The model gave it p=0.05p = 0.05, so L=−ln⁡0.05≈3.0L = -\ln 0.05 \approx 3.0. That confident miss costs nearly 60× as much. Training lowers the average LL over all rows by walking downhill, as in D09.

Try it

Fit the fraud curve yourself

Top row: fraud, label 1. Bottom row: legit, label 0. Move the curve so it sits near 1 over the top row and near 0 over the bottom row, and watch the log loss fall.

02400.51Payment amount ($100s)probability px = 0.2, legit, p = 0.858 (wrong side)x = 0.4, legit, p = 0.832 (wrong side)x = 0.6, legit, p = 0.802 (wrong side)x = 0.9, legit, p = 0.75 (wrong side)x = 1.2, legit, p = 0.69 (wrong side)x = 2.2, legit, p = 0.45x = 1.6, fraud, p = 0.599x = 2.5, fraud, p = 0.378 (wrong side)x = 3.1, fraud, p = 0.25 (wrong side)x = 3.8, fraud, p = 0.142 (wrong side)x = 4.5, fraud, p = 0.076 (wrong side)

p = σ(-1·x + 2)mean log loss 1.447right at p > 0.5: 2 of 11boundary x = 2

Points outlined in red are on the wrong side of the boundary.

The curve starts out sloping the wrong way, and the log loss is about 1.45. Make ww positive, then slide bb until the boundary sits between the legit and fraud points. You can get the loss to about 0.26 (near w=2.6w = 2.6, b=−5b = -5), but not to 0: the $220 legit payment and the $160 fraud overlap.

In code

scikit-learn's LogisticRegression finds the weights. This builds 2,000 seeded payments (about 15% fraud) and scores payments A, B and C.

# script_id: day_012_logistic_regression/fraud
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.metrics import log_loss

rng = np.random.default_rng(42)
fraud = (rng.random(2000) < 0.15).astype(int)                 # 1 = fraud, about 15%
X = pd.DataFrame({
    "amount": np.where(fraud, rng.uniform(100, 499, 2000), rng.lognormal(np.log(40), 1.0, 2000)),
    "km_from_home": np.where(fraud, rng.exponential(60, 2000), rng.exponential(10, 2000)),
})
line = LinearRegression().fit(X[["amount"]], fraud)
print("straight line, $5 and $800:", line.predict(pd.DataFrame({"amount": [5, 800]})).round(2))

model = LogisticRegression().fit(X, fraud)                     # C=1.0 by default
trio = pd.DataFrame({"amount": [100, 300, 500], "km_from_home": [10, 20, 30]})
print("score z:  ", model.decision_function(trio).round(2))
print("p(fraud): ", model.predict_proba(trio)[:, 1].round(3))
print("label:    ", model.predict(trio))
print(f"average log loss: {log_loss(fraud, model.predict_proba(X)):.3f}")
straight line, $5 and $800: [-0.03  1.43]
score z:   [-3.3  -0.11  3.08]
p(fraud):  [0.036 0.472 0.956]
label:     [0 0 1]
average log loss: 0.164

The learned scores are close to the hand-made ones. B lands just under 0.5, so predict calls it legit. C sets how hard the weights are held back, as in D11: a smaller C holds them back harder.

Quick check

Quick check

1. A payment scores z = 0. What chance of fraud does the model give?

2. A payment really is fraud (y = 1). Which prediction has the highest log loss?

3. Why not fit a straight line to 0/1 labels?

Next

The model said 0.47 for payment B; D13 shows how to pick the cut-off that turns a probability into a decision.

Next · Day 13 · 8 minClassification Metrics: Thresholds, ROC and PR Curves← Previous: Day 11 · Regularize with Ridge and Lasso
Not tapped yet