Module 17

Logistic Regression

Predicting binary outcomes

Classification with Regression

  • 01

    Binary Outcomes

    Yes/No, Pass/Fail, 0/1

  • 02

    The Logistic Function

    S-curves for probability

  • 03

    Odds Ratios

    Interpreting coefficients

  • 04

    Model Evaluation

    Accuracy, ROC, AUC

01

Why Logistic Regression?

Binary Outcomes Don't Fit Lines

Pass (1)Fail (0)
Linear regression predicts values < 0 and > 1!

With binary outcomes (0 or 1), linear regression fails: it can predict impossible values like -0.3 or 1.5. We need a model that outputs probabilities between 0 and 1.

The S-Curve Solution

10
S-curve stays between 0 and 1

The logistic (S-shaped) curve naturally stays between 0 and 1. It asymptotes to 0 and 1 but never crosses. The output is interpreted as P(Y=1)—probability of success.

When to Use Logistic Regression

🏥 Medical
Disease present/absent
Survival/death
Treatment response
💼 Business
Purchase yes/no
Churn yes/no
Fraud yes/no
🎓 Education
Pass/fail
Graduate/dropout
Admit/reject
🔬 Research
Success/failure
Present/absent
Yes/no responses

Use logistic regression whenever your outcome is binary (two categories). It's one of the most widely used methods in medicine, business, and social sciences.

02

The Logistic Function

The Math Behind the S-Curve

P(Y=1) = 1 / (1 + e^-(b₀ + b₁X))
Also written as: P = e^z / (1 + e^z) where z = b₀ + b₁X
Key property:
• When z → -∞, P → 0
• When z = 0, P = 0.5
• When z → +∞, P → 1

The logistic function transforms the linear combination (b₀ + b₁X) into a probability. No matter how large or small the input, output stays between 0 and 1.

The Logit Transformation

Odds = P / (1-P)
↓
Log-odds (logit) = ln(P / (1-P))
↓
logit(P) = b₀ + b₁X
Logistic regression is linear in log-odds!

The logit (log-odds) transformation linearizes the relationship. Logistic regression predicts log-odds as a linear function of X. This is why it's called 'linear' even though the probability curve is S-shaped.

What Coefficients Mean

b₁ = 0.5

"For each 1-unit increase in X, the log-odds of Y=1 increase by 0.5"

Or equivalently:
"The odds multiply by e^0.5 = 1.65"
b > 0
↑ X → ↑ P(Y=1)
b = 0
X doesn't affect P
b < 0
↑ X → ↓ P(Y=1)

Coefficients show change in log-odds per unit X. Positive b means higher X → higher probability of Y=1. The magnitude tells you how strongly X affects the outcome.

03

Odds Ratios

Understanding Odds

Probability
P(win) = 0.75
"75% chance of winning"
Odds
Odds = 0.75/0.25 = 3
"3 to 1 odds of winning"
Odds = P/(1-P) | P = Odds/(1+Odds)

Odds express probability differently. If P = 0.75, odds = 3 ("3 to 1 for"). Odds range from 0 to ∞. Odds = 1 means 50-50 chance. Odds > 1 means more likely than not.

Comparing Groups

OR = e^b
Example: Smoking → Lung Cancer

b = 1.6, so OR = e^1.6 = 4.95

Interpretation:
"Smokers have ~5× the odds of lung cancer compared to non-smokers"
OR < 1
Protective
OR = 1
No effect
OR > 1
Risk factor

The odds ratio (OR) = e^b. OR = 5 means the odds are 5 times higher. OR = 0.5 means odds are halved. OR = 1 means no effect. This is the standard way to interpret logistic coefficients.

Confidence Intervals for OR

95% CI for OR: [e^(b - 1.96×SE), e^(b + 1.96×SE)]
Example: b = 1.6, SE = 0.3

95% CI for b: [1.6 - 0.59, 1.6 + 0.59] = [1.01, 2.19]
95% CI for OR: [e^1.01, e^2.19] = [2.75, 8.94]

Conclusion: OR is between 2.75 and 8.94
Since CI doesn't include 1, effect is significant

The confidence interval for OR tells you the range of plausible effect sizes. If the CI doesn't include 1, the effect is statistically significant. Wider CI = more uncertainty.

How to Report Results

Example write-up:

"Logistic regression was used to predict heart disease from cholesterol level. Higher cholesterol significantly increased the odds of heart disease (OR = 1.08, 95% CI [1.03, 1.13], p = .001). For each 10 mg/dL increase in cholesterol, the odds of heart disease increased by 8%. The model correctly classified 73% of cases (AUC = 0.79)."

Report: OR with 95% CI, p-value, and direction of effect. Also report model fit (classification accuracy, AUC). ORs are much more interpretable than raw coefficients.

04

Model Evaluation

The Confusion Matrix

Predicted
PositiveNegative
Actual PositiveTP
True Positive
FN
False Negative
Actual NegativeFP
False Positive
TN
True Negative

The confusion matrix shows how predictions compare to reality. TP and TN are correct; FP (false alarm) and FN (missed detection) are errors. This is the foundation for many metrics.

Key Performance Metrics

Accuracy(TP + TN) / Total
Sensitivity (Recall)TP / (TP + FN)
SpecificityTN / (TN + FP)
PrecisionTP / (TP + FP)
Sensitivity: catch the positives | Specificity: avoid false alarms

Accuracy is overall correctness. Sensitivity (recall) is how well you catch positives. Specificity is how well you correctly identify negatives. The right metric depends on your goals.

ROC Curve and AUC

1 - Specificity (FPR)Sensitivity (TPR)AUC = 0.85
AUC: 0.5 = random | 0.7-0.8 = fair | 0.8-0.9 = good | >0.9 = excellent

The ROC curve plots sensitivity vs (1-specificity) at different thresholds. AUC (area under curve) summarizes performance: 0.5 is random guessing, 1.0 is perfect classification.

Choosing the Cutoff

Default threshold: P > 0.5 → Predict Y = 1
Lower threshold (e.g., 0.3)
• More positives predicted
• Higher sensitivity
• More false positives
• Use when missing cases is costly
Higher threshold (e.g., 0.7)
• Fewer positives predicted
• Higher specificity
• More false negatives
• Use when false alarms are costly

The default 0.5 threshold isn't always optimal. Lower it if missing positives is costly (disease screening). Raise it if false positives are costly (criminal conviction). Choose based on costs.

★

Real-World Examples

Apply your knowledge to practical scenarios

01

Predicting Customer Churn

A telecom company builds a logistic regression to predict customer churn. Model: logit(P) = -2.5 + 0.8(Complaints) + 0.05(MonthsWithService) - 0.3(SatisfactionScore). AUC = 0.82.

Sample Data
{
  "n": 5000,
  "churn_rate": 0.15,
  "AUC": 0.82
}
Q Calculate the odds ratio for Complaints (b = 0.8). +
A OR = e^0.8 = 2.23. Each additional complaint more than doubles the odds of churning (123% increase in odds).
Q Interpret the SatisfactionScore coefficient (b = -0.3). +
A OR = e^(-0.3) = 0.74. Each 1-unit increase in satisfaction DECREASES odds of churning by 26% (0.74 = 74% of original odds). Satisfaction is protective against churn.
Q A customer has 2 complaints, 24 months service, and satisfaction score of 3. What's their predicted probability of churning? +
A logit(P) = -2.5 + 0.8(2) + 0.05(24) - 0.3(3) = -2.5 + 1.6 + 1.2 - 0.9 = -0.6. P = e^(-0.6)/(1 + e^(-0.6)) = 0.55/(1.55) = 0.35. 35% probability of churning.
Q With AUC = 0.82, how good is the model? +
A AUC = 0.82 is 'good' (0.8-0.9 range). The model correctly ranks a random churner above a random non-churner 82% of the time. There's room to improve but it's useful.
Key Insights
  • Convert coefficients to odds ratios for interpretation: OR = e^b
  • Negative coefficients mean the factor REDUCES the odds of the outcome
  • AUC measures how well the model ranks cases—0.82 is good
02

Disease Screening Trade-offs

A hospital develops a logistic model to screen for a rare disease (prevalence 2%). At the default 0.5 cutoff: Sensitivity = 60%, Specificity = 95%. At a 0.2 cutoff: Sensitivity = 90%, Specificity = 80%.

Sample Data
{
  "prevalence": 0.02,
  "cutoff_05": {
    "sensitivity": 0.6,
    "specificity": 0.95
  },
  "cutoff_02": {
    "sensitivity": 0.9,
    "specificity": 0.8
  }
}
Q At the 0.5 cutoff with 60% sensitivity, what percentage of actual disease cases are missed? +
A 40% are missed (false negatives). Sensitivity = TP/(TP+FN) = 60%, so 40% of true cases are classified as negative. For a serious disease, this could be dangerous.
Q Why might the hospital choose the 0.2 cutoff despite lower specificity? +
A At 0.2 cutoff: 90% sensitivity catches most disease cases (only 10% missed). For a serious disease, missing cases (FN) is more costly than extra follow-up tests (FP). Lower threshold prioritizes catching cases.
Q At 0.2 cutoff with 80% specificity and 2% prevalence, what's the positive predictive value (PPV)? +
A In 10,000 people: 200 have disease, 9,800 don't. TP = 0.90 × 200 = 180. FP = 0.20 × 9,800 = 1,960. PPV = 180/(180+1960) = 180/2140 = 8.4%. Most positives are false alarms!
Q Why is PPV so low even with good sensitivity and specificity? +
A Low prevalence (2%). When the disease is rare, even small false positive rates generate many false positives in absolute terms. This is the base rate problem—PPV depends heavily on prevalence.
Key Insights
  • Threshold choice depends on costs: lower for serious conditions where missing cases is costly
  • Sensitivity and specificity don't tell the whole story—PPV depends on prevalence
  • Rare diseases: even 'accurate' tests have low positive predictive value
03

Credit Card Fraud Detection

A bank builds a fraud detection model. Fraud rate is 0.1% (rare!). At default 0.5 threshold: catches 40% of fraud, 99.9% specificity. They're considering lowering threshold but are concerned about customer complaints from false positives.

Q With 0.1% fraud rate and current model catching 40%, how many frauds per million transactions are missed? +
A Per million: 1,000 frauds (0.1%). Catching 40% means 600 missed. That's substantial losses—each fraud might be hundreds of dollars.
Q If they lower the threshold to catch 80% of fraud, but specificity drops to 99%, how many false positives per million? +
A Per million: 999,000 legitimate. At 99% specificity, 1% are false positives = 9,990 legitimate transactions flagged. That's nearly 10,000 angry customers per million transactions!
Q How should the bank balance this trade-off? +
A Calculate costs: If average fraud = $500, missing 600 = $300,000 loss. If false positive costs $5 (customer inconvenience, call center time), 9,990 FP = ~$50,000. At these costs, higher sensitivity might be worth it.
Q What makes fraud detection particularly challenging? +
A Extreme class imbalance (0.1% fraud). Accuracy is meaningless—predicting 'no fraud' for everyone gives 99.9% accuracy! Must focus on sensitivity/specificity and business costs.
Key Insights
  • With imbalanced classes, accuracy is misleading
  • Threshold selection requires explicit cost-benefit analysis
  • Rare events make false positives inevitable in absolute numbers
?

Logistic Regression Quiz

Test your understanding • Passing score: 70%

0 of 10 answered
Q1 multiple-choice

Why is logistic regression used instead of linear regression for binary outcomes?

Explanation: Linear regression can predict values < 0 or > 1, which are impossible for probabilities. Logistic regression's S-curve naturally bounds predictions between 0 and 1.
Q2 calculation

If b = 0.7 in logistic regression, what is the odds ratio?

Explanation: OR = e^b = e^0.7 = 2.01. Each 1-unit increase in the predictor approximately doubles the odds of the outcome.
Q3 multiple-choice

What does an odds ratio of 0.5 indicate?

Explanation: OR = 0.5 means the odds are halved. For each 1-unit increase in the predictor, the odds of the outcome become 50% of what they were—a protective effect.
Q4 multiple-choice

In the confusion matrix, what is a False Positive (FP)?

Explanation: False Positive (FP) = predicted positive but actually negative. It's a false alarm. For example, predicting someone has disease when they don't.
Q5 multiple-choice

Sensitivity (recall) is calculated as:

Explanation: Sensitivity = TP / (TP + FN) = True Positives / All Actual Positives. It measures how well you catch the positive cases.
Q6 multiple-choice

A model has AUC = 0.5. What does this mean?

Explanation: AUC = 0.5 means the model performs no better than random chance (flipping a coin). It cannot discriminate between positive and negative cases.
Q7 multiple-choice

When should you lower the classification threshold below 0.5?

Explanation: Lower the threshold when false negatives are costly (e.g., disease screening). This increases sensitivity (catches more positives) at the cost of more false positives.
Q8 multiple-choice

The 95% confidence interval for an odds ratio is [1.2, 3.5]. What can you conclude?

Explanation: Since the CI [1.2, 3.5] doesn't include 1, the effect is statistically significant. The odds are increased by between 20% and 250% with 95% confidence.
Q9 multiple-choice

In logistic regression, what does the logit function transform?

Explanation: The logit function transforms probability (bounded 0-1) into log-odds (unbounded -∞ to +∞). This allows the linear model to work on an unbounded scale.
Q10 multiple-choice

With class imbalance (1% positive, 99% negative), accuracy = 99% by predicting all negative. Is this model useful?

Explanation: With imbalanced classes, accuracy is misleading. Predicting all negative gives 99% accuracy but 0% sensitivity—you miss every positive case. Use sensitivity, specificity, and AUC instead.

Quiz Results

0 %

← Model Comparison Next: Missing Data →