Logistic Regression and Classification
Logistic regression is a classification model that predicts a probability. It computes a weighted sum of the features, like linear regression, then squeezes it through the sigmoid function into a number between 0 and 1. A threshold, usually 0.5, turns the probability into a category. Despite its name, it is used for classification, and it is one of the most common models in practice.
From Score to Probability
| Part | Description |
|---|---|
| Coefficient | It is used to show which way a feature moves the chance: positive raises it |
predict_proba() | It is used to get each class's probability |
| Threshold | It is used to turn a probability into a decision |
| Recall | It is used to measure how many of the real positives (late payers) are caught |
Example
This program uses payments_history.csv from "Supervised Learning".
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, recall_score
from sklearn.model_selection import train_test_split
data = pd.read_csv("payments_history.csv")
X, y = data.drop(columns="late"), data["late"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
for name, coef in zip(X.columns, model.coef_[0]):
print(f"{name:16} {coef:6.2f}")
families = pd.DataFrame([
{"amount": 250, "past_late": 2, "autopay": 0, "months_enrolled": 6, "opened_reminder": 0},
{"amount": 45, "past_late": 0, "autopay": 1, "months_enrolled": 30, "opened_reminder": 1},
])
for chance in model.predict_proba(families)[:, 1]:
print(f"Chance of paying late: {chance:.1%}")
chance = model.predict_proba(X_test)[:, 1]
for threshold in [0.5, 0.3]:
predicted = (chance >= threshold).astype(int)
print(f"threshold {threshold}: accuracy {accuracy_score(y_test, predicted):.1%}, "
f"late payers caught {recall_score(y_test, predicted):.0%}")amount 0.01
past_late 1.34
autopay -2.46
months_enrolled -0.02
opened_reminder -0.89
Chance of paying late: 91.6%
Chance of paying late: 0.2%
threshold 0.5: accuracy 89.6%, late payers caught 39%
threshold 0.3: accuracy 89.2%, late payers caught 61%Explanation: Each coefficient shows a feature's direction: each past late payment raises the chance, while autopay lowers it the most. The first family has a 91.6% chance of paying late; the second only 0.2%. With the usual 0.5 threshold, the model catches only 39% of the families who really paid late. Lowering the threshold to 0.3 catches 61% while accuracy barely changes, because the threshold decides how many families get flagged.
Choosing the Threshold
| Threshold | Effect | Good when |
|---|---|---|
| High (0.7) | Flags few families; few false alarms | Acting is costly, such as a phone call from staff |
| Middle (0.5) | The default balance | No strong preference |
| Low (0.3) | Flags more families; catches more late payers | Acting is cheap, such as an extra reminder email |
Common Mistakes
Using the default 0.5 without thinking. Pick the threshold for the decision.
Comparing raw coefficients across features on different scales. Scale features first if you want to compare them.
Treating a probability as certain. A 91.6% chance of paying late still means about one family in twelve like this pays on time.
Interview Corner
How does logistic regression produce a classification?
It computes a weighted sum of features, converts it to a probability with the sigmoid function, and compares the probability with a threshold.
What is recall, and why can it matter more than accuracy?
Recall is the share of real positives the model catches. When positives are rare and important, such as late payments or fraud, a model can be highly accurate while missing most of them.
Practice
Exercise: try thresholds. Print accuracy and recall for thresholds 0.2, 0.4 and 0.6. Which would you choose if each missed late payment costs the school $10 in follow-up, and each extra reminder costs nothing?
Check your understanding:
- What does the sigmoid function do?
- Which feature lowers the chance of paying late the most?
- Why did lowering the threshold catch more late payers?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| Model | LogisticRegression(max_iter=1000) |
| Probabilities | model.predict_proba(X)[:, 1] |
| Own threshold | (chance >= 0.3).astype(int) |
| Recall | recall_score(y_test, predicted) |
Was this tutorial helpful?