Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 86/ 160
05. Classical Machine Learning

Logistic Regression

Classify with sigmoid probabilities, log-loss, and interpretable coefficient odds ratios.

BeginnerSigmoid · Log-loss3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Logistic regression adds up weighted clues about a customer and turns the total into a chance (0 to 100%) that something will happen, such as leaving.

Think of it like…

A dimmer switch rather than an on-off switch: the linear score is the dial position and the sigmoid turns it into a smooth probability between 0 and 1, which you then compare with a threshold chosen for the cost of mistakes.

Where you’ve seen it

A churn model has β₀ = −1.2, a coefficient of +0.8 per open support ticket and −0.05 per month of tenure. For a customer with 3 tickets and 10 months of tenure, z = −1.2 + 0.8 × 3 − 0.05 × 10 = 0.7, so p = σ(0.7) = 0.668 (odds 2.01 to 1). Each extra ticket multiplies the odds by e^0.8 = 2.23, and each month of tenure by e^−0.05 = 0.951 (12 months: e^−0.6 = 0.549). The log-loss for this customer is −ln(0.668) = 0.403 if they churn and −ln(0.332) = 1.103 if they stay. A retention offer costs $20 and a lost customer costs $200, so the cost-minimising threshold is 20 / (20 + 200) = 0.091: contact anyone with churn probability above 9.1%, far below 0.5. The model is trained with L2 regularisation (C=1.0 by default in scikit-learn), standardised features and class weights evaluated against PR-AUC and a calibration curve.

Words you’ll hear

Sigmoid / logit
σ(z) maps a score to a probability; logit is its inverse, ln(p / (1 − p)).
Odds ratio
The multiplicative change in odds for a one-unit feature increase, e^β.
Log-loss
Cross-entropy loss that penalises confident wrong probabilities heavily.
Decision threshold
The probability cut-off for acting, chosen from error costs, not fixed at 0.5.

Visual diagram

Loading interactive diagram

Theory & deep dive

The model, loss and interpretation

The model assumes the log-odds are linear in the features: ln(p / (1 − p)) = β₀ + β·x. Fitting maximises the likelihood, equivalently minimises the log-loss averaged over rows, a convex problem solved by gradient methods (the gradient is Xᵀ(p − y)), L-BFGS or Newton-type solvers. Log-loss rewards calibrated probabilities and punishes confident mistakes: predicting 0.99 for an actual negative costs −ln(0.01) = 4.6, while 0.7 costs 1.2. Scikit-learn adds an L2 penalty by default with strength 1/C (smaller C means stronger regularisation), which also keeps coefficients finite when classes are perfectly separable (without a penalty the coefficients diverge to infinity).

Interpret coefficients on the odds scale: e^β is the factor by which the odds change per unit increase, holding other features fixed (support tickets: e^0.8 = 2.23 times higher odds per ticket). Odds ratios are not risk ratios, and the effect on the *probability* depends on where you start (the sigmoid's slope is largest near 0.5). Standardise features to compare coefficient sizes, and include interactions or splines if the log-odds are not linear in a feature. Multicollinearity inflates standard errors just as in linear regression, and statsmodels' Logit provides inference (p-values, confidence intervals), while scikit-learn focuses on prediction.

Probability from a score

z = −1.2 + 0.8 × 3 − 0.05 × 10 = 0.7. p = 1 / (1 + e^−0.7) = 1 / (1 + 0.4966) = 0.668. Odds = e^0.7 = 2.01, so about two churners for every non-churner among customers like this one.

Key takeaway: Logistic regression is linear in log-odds; read coefficients as odds ratios and regularise to keep fits stable.

Thresholds, imbalance, calibration and pitfalls

The model outputs probabilities; decisions need a threshold. With cost C_FP for a false positive and C_FN for a false negative, the expected-cost-minimising threshold on a calibrated probability is C_FP / (C_FP + C_FN), here 20 / 220 = 0.091. Choose it on validation data by maximising expected value or by a business constraint (contact at most 10% of customers, or fix precision at 40%), and report ROC-AUC, PR-AUC (more informative with rare positives), precision, recall and F1 at the chosen threshold. Handle class imbalance with class weights or resampling if it improves the metric you care about, but note that reweighting distorts probabilities; either recalibrate or just tune the threshold on the unweighted model.

Check calibration with a reliability curve (calibration_curve): do customers scored 0.3 churn about 30% of the time? If not, recalibrate with Platt scaling (CalibratedClassifierCV(method="sigmoid")) or isotonic regression. Pitfalls: unscaled features slow convergence and make the penalty uneven; leakage inflates AUC; extrapolating to feature ranges unseen in training; interpreting odds ratios as probability changes; ignoring separation (perfectly predictive feature) that makes coefficients explode; and nonlinear or interacting effects that a plain linear log-odds model misses (add terms, or compare with a gradient-boosted model as a sanity check). For more than two classes use multinomial (softmax) logistic regression, which outputs a probability per class summing to 1.

Cost-based threshold

False positive (unneeded offer) costs $20; false negative (lost customer) costs $200. Threshold = 20 / (20 + 200) = 0.091. A customer with p = 0.15 gets the offer (expected loss without it: 0.15 × 200 = $30 versus $20 for the offer), though a 0.5 threshold would have skipped them.

Key takeaway: Choose the threshold from costs, evaluate with PR-AUC and calibration, and watch for separation and nonlinearity.

How it works, step by step

Step 1 of 4
Analyst

1. Prepare features

Impute, scale and encode inside a pipeline; add interactions or splines where log-odds are curved.

StandardScaler + LogisticRegression
Key numbers at this step
C
inverse penalty strength

When to use it & trade-offs

What it is

Logistic regression models the probability of a binary outcome as p = σ(z) = 1 / (1 + e^(−z)), where z = β₀ + β₁x₁ + ... is a linear score (the log-odds). It is trained by minimising log-loss (cross-entropy), −[y ln p + (1 − y) ln(1 − p)], usually with an L2 penalty, and its coefficients are interpretable: a one-unit increase in a feature multiplies the odds by e^β (the odds ratio). Predictions are probabilities that you turn into decisions by choosing a threshold based on the costs of errors. It is the standard baseline for classification, fast to train and easy to explain, and it extends to many classes with softmax.

Why it matters: Many business problems (churn, default, conversion, fraud, click) are binary with costs that differ by error type, so calibrated probabilities and a tunable threshold matter more than a default 0.5 cut-off. Logistic regression gives both, plus coefficients that regulators and stakeholders can read. Understanding its loss, assumptions and threshold choice is the base for understanding neural network output layers, boosting objectives and calibration.

When to reach for it

  • Churn, default, conversion and fraud scoring
  • Regulated settings that need explainable models
  • A baseline before trying complex models

When to avoid or be careful

  • Using a 0.5 threshold regardless of costs
  • Reporting accuracy on rare-event data
  • Interpreting odds ratios as changes in probability

Classifiers for binary problems

Logistic regression
Best for: Interpretable, calibrated baselines

Strengths: Fast; probabilities; coefficients explain effects.

Watch out: Linear log-odds; needs feature engineering for interactions.

Gradient-boosted trees
Best for: Complex interactions in tabular data

Strengths: High accuracy with little feature engineering.

Watch out: Less interpretable; needs calibration.

Naive Bayes
Best for: Very fast text baselines

Strengths: Trains in one pass; works with little data.

Watch out: Over-confident probabilities.

Interview signals & numbers to know

When this topic comes up

  • “What is the probability this customer churns?”
  • “Interpret the coefficient”
  • Odds ratio
  • Log-loss
  • Calibration curve

Benchmarks & rules of thumb

σ(0.7) = 0.668 -
probability from a log-odds score of 0.7
e^0.8 = 2.23 -
odds multiplier for a coefficient of 0.8
C_FP / (C_FP + C_FN) -
cost-optimal threshold on calibrated probabilities

Common mistakes & follow-ups

Common interview mistakes

  • Using class weights and then treating the probabilities as calibrated.
  • Leaving a perfectly separating feature unregularised.
  • Comparing coefficients of unscaled features.

Likely interviewer follow-ups

  • How do you interpret a logistic regression coefficient?
  • How do you choose the classification threshold?
  • Why use log-loss instead of squared error?
Interview tip: Compute a probability from a score and derive the threshold from costs. It shows you can go from model output to a business decision.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Logistic Regression with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Regularization (Ridge, Lasso, ElasticNet)
Next topic
K-Nearest Neighbors (KNN)