Logistic Regression & Classification
Convert evidence into probabilities, probabilities into decisions and decisions into measurable outcomes. Learn classification mathematics, thresholds and evaluation from first principles.
By the End of This Level, You Can
Six Ideas Before Classification
Classification begins with probability, linear scores and honest evaluation.
Encode the two outcomes consistently.
Confidence before a decision threshold.
Weighted evidence before sigmoid.
Turns likelihood products into sums.
Preserve class proportions when appropriate.
Different mistakes often have different consequences.
Classification Predicts Categories
A classifier estimates evidence for discrete outcomes instead of predicting an unrestricted number.
Prioritize the cost of a missed positive diagnosis.
Severe imbalance makes accuracy misleading.
Thresholds balance unwanted mail and missed spam.
Use only evidence available before the outcome.
Classification predicts a discrete outcome such as fraud or not fraud. Many classifiers first estimate scores or probabilities and then apply a decision rule. Defining the positive class and cost of each error is essential because category labels alone do not describe operational consequences.
Spam detection, disease screening and defect recognition are classification tasks, even though their false-positive and false-negative costs differ greatly.
Classification interviews commonly test decision policy, not only algorithm syntax.
Turning every probability above 0.5 into class 1 is a convention, not a universal rule.
Odds and Log-Odds
Logistic regression models the logarithm of class odds as a linear function.
p = P(y=1|x)A value from 0 to 1.
p / (1−p)How much more likely class 1 is than class 0.
log(p/(1−p)) = wᵀx+bAn unrestricted linear score from −∞ to +∞.
xⱼ by one unit multiplies the odds by eʷʲ, holding other modeled features constant.Odds compare the probability of an event with the probability of it not occurring: p/(1-p). Log-odds apply the logarithm, mapping probabilities between 0 and 1 onto the complete real line. Logistic regression models log-odds as a linear combination of features.
Probability 0.8 corresponds to odds 4:1 and log-odds ln(4), approximately 1.386.
A one-unit feature increase multiplies the odds by exp(weight) when other features remain fixed.
Odds and probability are related but not numerically interchangeable.
The Sigmoid Function
Sigmoid converts any real-valued score into a valid probability.
σ(z) = 1 / (1 + e⁻ᶻ)- z → −∞: probability approaches 0.
- z = 0: probability equals 0.5.
- z → +∞: probability approaches 1.
The sigmoid function maps any real score to a value between 0 and 1. A score of zero maps to 0.5; large positive scores approach 1 and large negative scores approach 0. Its derivative p(1-p) supports gradient-based learning.
Scores -2, 0 and 2 produce probabilities of about 0.119, 0.5 and 0.881.
Sigmoid is used for independent binary outputs and the final probability in binary logistic regression.
Extreme scores can cause numerical overflow or log(0); use stable library implementations and clipped probabilities.
Logistic Model and Decision Boundary
The probability is curved, but the default boundary occurs where the linear score equals zero.
z = w₁x₁ + w₂x₂ + bp = σ(z)p ≥ 0.5 ⇔ z ≥ 0The equation w₁x₁ + w₂x₂ + b = 0 defines a line in 2D, a plane in 3D and a hyperplane in higher dimensions.
Logistic regression forms a linear score z=w·x+b and transforms it with sigmoid. The threshold determines the boundary: at threshold 0.5, z=0. In multiple dimensions the score boundary is a line, plane or hyperplane even though the probability changes nonlinearly.
For one feature with positive weight, larger x values receive larger probabilities and cross the decision threshold at a calculable x.
Feature scaling and regularization affect optimization and coefficient stability.
The name contains regression because log-odds are modelled continuously, but the usual task is classification.
Binary Cross-Entropy: Learn Probabilities
Log loss strongly penalizes confident wrong probabilities and is the negative log-likelihood for Bernoulli outcomes.
−[y log(p) + (1−y)log(1−p)]The loss becomes −log(p); higher predicted probability for class 1 reduces loss.
The loss becomes −log(1−p); lower predicted probability for class 1 reduces loss.
Binary cross-entropy rewards high probability on the true class and applies a rapidly increasing penalty to confident wrong predictions. It is the negative log-likelihood of Bernoulli outcomes. Averaging it across samples creates a smooth objective for logistic-regression training.
For a true positive label, predicting 0.9 has low loss while predicting 0.01 has very large loss.
Cross-entropy trains probability estimates, whereas accuracy changes only after a thresholded class decision.
A lower training cross-entropy does not guarantee calibrated or generalizable probabilities.
Optimization and Regularization
Gradient descent adjusts coefficients using probability error; regularization controls flexibility.
pᵢ = σ(wᵀxᵢ+b)dw = (1/n)Xᵀ(p−y)db = mean(p−y)w ← w − αdwb ← b − αdbloss + λ penalty(w)Scale features before comparing or penalizing coefficients.
The cross-entropy gradient simplifies to prediction probability minus true label, multiplied by each feature for weight gradients. Gradient descent updates weights and bias across repeated batches. L1 or L2 regularization controls coefficient size and can improve stability under correlated or noisy features.
A positive example predicted with low probability produces a negative error that pushes its score upward.
Tracing one batch reveals how every sample contributes to the final parameter update.
Regularization strength must be validated, and preprocessing must be fitted inside the same pipeline.
A Threshold Converts Probability into Action
The default 0.5 threshold is convenient—not automatically optimal.
Usually catches more positives: recall rises, but false positives may increase.
Usually demands stronger evidence: false positives fall, but positives may be missed.
A threshold converts an estimated probability into an action. Lowering it predicts more positives, usually increasing recall and false positives; raising it predicts fewer positives, often increasing precision while missing more positives. Select it using validation data and explicit costs or constraints.
A screening system may use a lower threshold to avoid missing disease, followed by a specific confirmatory test.
Thresholds can differ by workflow stage but require fairness, calibration and capacity checks.
Do not tune the threshold on the final test set or choose it only to maximize accuracy.
The Confusion Matrix
Every binary decision belongs to one of four outcomes.
The confusion matrix counts true positives, true negatives, false positives and false negatives for a defined positive class and threshold. It is the source of most classification metrics. Counts show workload and harm; normalized rates support comparison across datasets.
In disease screening, a false negative is an affected patient incorrectly predicted negative.
Reading the matrix correctly is one of the most common placement calculations.
Changing which class is positive changes precision, recall and the interpretation of every error.
Classification Metrics and Their Questions
Start with the decision question, then select a metric.
(TP+TN)/AllHow often is the classifier correct overall?
TP/(TP+FP)When it predicts positive, how often is it right?
TP/(TP+FN)Of all real positives, how many were found?
TN/(TN+FP)Of all real negatives, how many were rejected?
2PR/(P+R)What is the harmonic balance of precision and recall?
(Recall+Specificity)/2How well are both classes recognized?
Accuracy asks what fraction was correct. Precision asks how many predicted positives were truly positive. Recall asks how many real positives were found. Specificity asks how many real negatives were rejected. F1 balances precision and recall through their harmonic mean.
Fraud review capacity may prioritize precision, while safety screening may prioritize recall.
Choose metrics from the decision cost, class prevalence and workflow capacity.
F1 ignores true negatives and may be inappropriate when correctly rejecting negatives is important.
ROC-AUC and PR-AUC Across Thresholds
Ranking metrics summarize many thresholds but answer different questions.
Useful for ranking; can look optimistic when negatives dominate.
Often more informative when the positive class is rare.
ROC curves compare true-positive and false-positive rates across thresholds; ROC-AUC measures ranking across random positive–negative pairs. Precision–recall curves focus on positive predictions and are often more informative when positives are rare. Neither curve selects the final operating threshold by itself.
Two models can have similar ROC-AUC but very different precision at the recall required by the application.
Report the curve and a validated operating point aligned with business constraints.
AUC summarizes all thresholds, including many that would never be used in practice.
Class Imbalance and Cost-Sensitive Decisions
A 99% accurate classifier can be useless when positives form only 1% and the model predicts everything negative.
Use grouped or time-aware alternatives when the data structure requires them.
Class weights change training loss, not the real data distribution.
Oversampling, undersampling or SMOTE must remain inside validation.
Select with validation data and deploy an explicit policy.
Imbalanced learning combines suitable splits, metrics, weighting, training-only resampling and threshold decisions. Class weighting changes the training objective; resampling changes the training distribution; thresholding changes the decision policy. These are related but not equivalent interventions.
A weighted loss can make rare fraud errors matter more without duplicating transactions.
Probability calibration may be affected by resampling and should be checked on representative validation data.
Applying SMOTE or oversampling before the split leaks synthetic relatives into evaluation data.
Multiclass Logistic Regression
Extend binary decisions to three or more mutually exclusive classes.
Compare each class against all others, then choose the strongest score.
Exponentiate class scores and normalize so probabilities sum to one.
pₖ = eᶻᵏ / ΣⱼeᶻʲUse independent outputs and thresholds; it is not ordinary multiclass classification.
One-vs-rest trains one binary classifier per class and selects the strongest score. Multinomial logistic regression uses softmax so class probabilities compete and sum to one. The best choice depends on class relationships, solver support, data size and whether labels are mutually exclusive.
Handwritten digit recognition has ten mutually exclusive classes and naturally supports a softmax output.
Softmax generalizes logistic normalization from two classes to several competing classes.
Multiclass and multilabel problems are different: multilabel samples can belong to several classes simultaneously.
Probability Calibration
A calibrated model makes probability statements that match observed frequencies.
Group predictions into probability bins and compare predicted with observed rate.
Evaluate probability quality, not only hard classifications.
Fit calibration on held-out or cross-validated predictions.
A calibrated model assigns probabilities that match observed frequencies: among cases predicted near 0.7, roughly 70% should be positive. Reliability diagrams, Brier score and calibration error assess this property. Platt scaling or isotonic regression can recalibrate using separate validation evidence.
Two models may rank patients equally well, but only the calibrated model supports meaningful risk communication.
Calibration matters when probabilities drive pricing, triage or resource allocation.
A model can have excellent AUC and poor calibration because ranking and probability accuracy are different.
The CodeBhavya Classification Workflow
Separate model probability, decision policy and business outcome.
- 01Frame
Define positive class, unit, cutoff time and error costs.
- 02Split
Protect evidence with stratification, groups or time.
- 03Baseline
Compare class and probability baselines.
- 04Pipeline
Fit preprocessing inside validation folds.
- 05Train
Optimize cross-entropy and tune regularization.
- 06Threshold
Select an operating point using validation costs.
- 07Audit
Inspect calibration, subgroups and failure cases.
- 08Monitor
Track drift, prevalence, metrics and threshold impact.
model = Pipeline([
("prepare", preprocess),
("classifier", LogisticRegression(class_weight="balanced"))
])
model.fit(X_train, y_train)
probability = model.predict_proba(X_validation)[:, 1]
prediction = (probability >= chosen_threshold).astype(int)
A responsible classification workflow defines the positive class and action, protects the split, creates a simple baseline, trains a leakage-safe probability model, evaluates ranking and calibration, chooses a threshold from costs, checks subgroups and monitors prevalence and error drift after deployment.
A fraud system may rank transactions, select a review threshold from daily capacity and maintain a second rule for immediate blocking.
This workflow connects algorithm knowledge to placement-level system thinking.
An impressive offline score is insufficient when labels are delayed, users adapt or the decision changes the future data.
🎬 Evidence to Classification — Visual Flow
Trace a classifier from observations and scores to sigmoid probability, threshold and evaluation.
Observe labeled examples
Training examples show two outcomes across the feature space.
Trace Logistic Regression from Scratch
Follow each epoch, sigmoid probability, error, accumulated gradient and parameter update.
—Waiting for print(...)
Batch Logistic Gradient Descent
The nested loop exposes every probability and gradient contribution.
x = [-1.0, 0.0, 1.0]
y = [0, 0, 1]
weight = bias = 0.0
rate = 0.5
for epoch in range(2):
dw = db = 0.0
for xi, yi in zip(x, y):
score = weight * xi + bias
probability = 1 / (1 + exp(-score))
error = probability - yi
dw += error * xi
db += error
weight -= rate * dw / len(x)
bias -= rate * db / len(x)
print(round(weight, 2), round(bias, 2))0.32 -0.16- Sigmoid starts every probability at 0.5.
- Positive and negative samples push the gradient differently.
- Each batch update occurs only after all three samples.
- The weight becomes positive for the increasing class pattern.
Build Probability and Classification Skills
Attempt each problem independently. Workspaces and model programs remain collapsed initially.
Test Classification Decisions
Select one answer per question. Results show your answer, the correct answer and an explanation.
How Classification Appears in Hiring Rounds
Strong answers connect probability, threshold, metrics and business consequences.
Math and Intuition
Explain sigmoid, log-odds and cross-entropy.
Metric Calculation
Derive precision, recall, F1 and specificity from a matrix.
Scenario Decision
Choose a threshold and metric for fraud, medicine or spam.
Production Audit
Handle imbalance, calibration, drift and subgroup errors.
🎤 Logistic Regression & Classification — Interview Questions
Answer aloud before selecting Show Answer for each explanation.
Responsible Classification in One View
Combine features into evidence.
Map evidence through sigmoid.
Apply a validated threshold.
Measure the mistakes that matter.
A classifier is not only a model—it is a probability estimate plus a decision policy and its consequences.
Habits of Strong Classification Practitioners
Name the positive class explicitly before discussing precision or recall.
Inspect confusion matrices as counts and normalized rates.
Select thresholds on validation data—not the final test set.
Use PR curves and cost analysis for rare positive outcomes.
Check probability calibration before using risk scores operationally.
Monitor class prevalence because it can change precision after deployment.
Strengthen Classification Reasoning
Explain the decision and consequence before writing code.
- 01
Calculate sigmoid probabilities for scores −2, 0 and 2.
- 02
Convert probabilities [0.2, 0.55, 0.8] using thresholds 0.5 and 0.7.
- 03
Compute binary cross-entropy for y=1 and p=0.8.
- 04
Derive logistic-regression gradients using the chain rule.
- 05
Construct a confusion matrix from eight actual and predicted labels.
- 06
Calculate accuracy, precision, recall, specificity and F1.
- 07
Choose the primary metric for cancer screening and justify it.
- 08
Explain why accuracy fails for 1% fraud prevalence.
- 09
Compare ROC-AUC and PR-AUC for rare positives.
- 10
Design a validation procedure for threshold selection.
- 11
Compare one-vs-rest and multinomial logistic regression.
- 12
Plan calibration and drift monitoring for a risk classifier.
