MLDay 12 of 50Supervised and Unsupervised Learning
Logistic Regression
Your bank blocks every card payment over $500, so fraudsters charge $480 instead.
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.
- Score. Add up weighted features plus a bias, exactly like linear regression. The score can be any number, like −7 or +12.
- Squash. The sigmoid, an S-shaped curve, turns the score into a probability 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 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 | (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.
| Symbol | Meaning |
|---|---|
| the score: (weights times features, plus the bias) | |
| the sigmoid function | |
| Euler's number, about 2.718 | |
| the predicted chance of class 1 (fraud) |
Worked, payment C: gives .
Log loss scores one prediction against the true label. It's the negative log of the chance given to the right answer.
| Symbol | Meaning |
|---|---|
| the loss for one row; 0 is perfect, higher is worse | |
| the true label: 1 for fraud, 0 for legit | |
| the predicted chance of fraud | |
| the natural log |
Worked: C really is fraud (), so . Now say A was fraud too, a thief testing a stolen card. The model gave it , so . That confident miss costs nearly 60× as much. Training lowers the average 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.
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 positive, then slide until the boundary sits between the legit and fraud points. You can get the loss to about 0.26 (near , ), 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.