Part 04 / Topic 4 of 6
Logistic regression
For yes/no questions (churn or not), wrap the linear score in a sigmoid, which squashes any number into (0, 1) — a probability:
sigmoid(z) = 1 / (1 + exp(-z))
# sigmoid of [-4, -1, 0, 1, 4] -> [0.018, 0.269, 0.5, 0.731, 0.982]
The loss becomes log loss (cross-entropy): the negative log probability assigned to the true answer. Its gradient has the same clean shape as before, so the training loop barely changes:
# examples/02_logistic_regression_from_scratch_on_the.py
import numpy as np
from ailab import make_churn
df = make_churn().dropna()
X = df[["tenure_months", "monthly_charges", "support_calls"]].to_numpy()
X = (X - X.mean(axis=0)) / X.std(axis=0)
X = np.c_[X, (df["contract"] == "month-to-month").to_numpy()]
y = df["churned"].to_numpy()
w = np.zeros(X.shape[1]); b = 0.0
for _ in range(3000):
p = 1 / (1 + np.exp(-(X @ w + b)))
w -= 0.1 * X.T @ (p - y) / len(y)
b -= 0.1 * (p - y).mean()
acc = ((p > 0.5) == y).mean()
print("weights (tenure, charges, calls, month-to-month):", w.round(2))
print("training accuracy:", round(acc, 3))
print("baseline (always predict majority):", round(max(y.mean(), 1 - y.mean()), 3))
# weights (tenure, charges, calls, month-to-month): [-0.72 0.47 0.48 1.82]
# training accuracy: 0.77
# baseline (always predict majority): 0.702
Read the weights like a story: longer tenure lowers churn risk (−0.72); higher charges, more support calls and month-to-month contracts raise it. And the Part 3 habit pays off immediately: 0.77 only means something next to the 0.702 baseline.
p > 0.5 is a decision threshold — a choice, not a law. Part 6 shows how moving it trades precision against recall.
🧪 Quick quiz
- Logistic regression outputs…
Show the answer
A probability between 0 and 1, via the sigmoid function. You then pick a threshold (often 0.5) to turn it into a class.
Done here? The practice set for Part 4 — 4 exercises with solutions — is on the part page.