Skip to main content
LearnMLAcademy
Intermediate10 min read

Logistic Regression

Master logistic regression, sigmoid activation, and decision boundaries, with Python code, architecture diagrams, worked examples, and interview quiz.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Logistic Regression

Logistic Regression is a classification algorithm used to predict categorical outcomes.

It is used to predict categories such as:

  • Spam or Not Spam
  • Disease or No Disease
  • Fraud or Legitimate
  • Pass or Fail
  • Customer Will Buy or Not Buy

Logistic Regression is a widely used baseline because it is relatively simple, fast to train, and often interpretable. It is used in areas such as healthcare, finance, marketing, and cybersecurity.

Logistic Regression in Simple Words

Think of Logistic Regression as a model that first gives a new example a score, converts that score into an estimated probability, and then compares that probability with a threshold to choose a class.

Student Data
Score
Sigmoid
Probability
Pass / Fail
Study HoursAttendanceKnown Result
155%Fail
265%Fail
482%Pass
590%Pass

A new student arrives.

Suppose the trained model estimates:

Probability of Pass = 0.82

If our chosen threshold is 0.50, then 0.82 ≥ 0.50, so the model predicts Pass. Later in this lesson you will see where that probability comes from.


What is Logistic Regression?

Logistic Regression is a supervised machine learning algorithm used for predicting probabilities and classifying data into categories.

Simple Beginner Definition

INPUT DATA↓CALCULATE PROBABILITY↓ASSIGN CLASS LABEL

Bank Loan (Finance)

Suppose a bank wants to predict whether a customer will repay a loan. Input features are Salary, Age, Credit Score, and Loan Amount.

YESWill RepayorNOWill Not Repay

The model learns patterns to predict the probability of repayment.

Diabetes (Healthcare)

Suppose a hospital wants to predict whether a patient has diabetes. Input features are Age, BMI, Blood Pressure, and Glucose Level.

YESDiabetesorNONo Diabetes

The model learns patterns from patient records and predicts new cases.

Where Logistic Regression Fits

Machine Learning
Broad field
Supervised Learning
Learns from labelled examples
Classification
Predicts a class
Logistic Regression
Linear probabilistic classifier

Why Logistic Regression is Needed

Linear Regression works well for predicting numbers but fails for classification. Suppose we use Linear Regression for spam detection.

Linear Regression Problem

Possible continuous outputs:

  • -2.3
  • 4.7
  • 12.5

These values do not represent probabilities.

Logistic Regression Solution

Uses the Sigmoid Function. We need outputs strictly between:

0 and 1

Produces model-estimated probabilities that can be converted into class decisions.

FeatureRegressionClassification
OutputContinuous numberCategory
ExampleHouse priceSpam/Not Spam
AlgorithmsLinear RegressionLogistic Regression

Logistic Regression Workflow

Input Features
↓
Linear Combination
↓
Apply Sigmoid
↓
Generate Prob
↓
Assign Class Label

Types of Logistic Regression

1. Binary

Used when there are only two classes.

  • YES / NO
  • TRUE / FALSE
  • SPAM / NOT SPAM

2. Multinomial

Used when there are multiple categories.

  • Cat
  • Dog
  • Horse
  • Tiger

3. Ordinal Logistic Regression

A related specialized extension for ordered outcomes. Standard logistic-regression APIs do not automatically use the order.

  • Low
  • Medium
  • High

Core Idea of Logistic Regression

Logistic Regression first calculates a linear equation similar to Linear Regression.

Linear Equation

z = b₀ + b₁x₁ + b₂x₂ + ... + bₙxₙ

where z = linear output, b₀ = intercept, b₁, b₂ = coefficients, x₁, x₂ = features

Worked Example

Suppose b₀ = -3, b₁ = 1, x = 4

z = -3 + 1(4)

z = -3 + 4

z = 1

But 1 is still a score, not yet a probability.

So Logistic Regression applies the Sigmoid Function.

The Sigmoid Function

The sigmoid function converts linear values into probabilities strictly between 0 and 1.

Figure 9 — Sigmoid Function σ(z) = 1 / (1 + e⁻ᶻ)
Decision boundary (0.5)00.250.50.751.0z = w·x + bσ(z) — Probability→ Predict Class 0→ Predict Class 1

Sigmoid Formula

σ(z) = 1 / (1 + e⁻ᶻ)

How it limits output to 0..1:

  • e is Euler's number (≈ 2.718).
  • When z is highly positive, e⁻ᶻ becomes very small, making the denominator ≈ 1, so the output approaches 1.
  • When z is highly negative, e⁻ᶻ becomes huge, making the denominator huge, so the output approaches 0.
  • When z = 0, e⁰ = 1, making the output 1 / (1+1) = 0.5.

Why Sigmoid is Used

  • Converts numbers into probabilities: Ensures outputs are strictly between 0 and 1.
  • Smooth and differentiable: This makes the model convenient to optimize with gradient- or Newton-style numerical methods.
  • Monotonic: A larger linear score always maps to a larger estimated probability. The decision boundary remains linear in the features unless we first create nonlinear features.

Three Easy Sigmoid Values to Remember

zσ(z)Meaning
-2≈ 0.119Closer to Class 0
00.500Middle point
2≈ 0.881Closer to Class 1

As z increases, the sigmoid probability increases smoothly. You do not need to memorize the whole curve; understand the direction.

Interactive Lab

Sigmoid & Decision Threshold Explorer

See how changing Weights (w), Bias (b), and Decision Threshold (T) converts continuous linear scores into probabilities and binary classes.

Active Sigmoid Equation:
P(y=1) = 1 / (1 + e-(1.2·x - 6.0))
Decision Boundary: Predict Class 1 when P(y=1) ≥ 0.50 (x ≈ 5.00)
1.2
0.2 (Gentle)3.0 (Sharp Step)
-6.0
-12.0 (Shift Right)+2.0 (Shift Left)
0.50
0.10 (High Recall / More Positives)0.90 (High Precision)

Confusion Matrix on 10 Sample Patients

Acc: 100%
True Negative (TN)5
False Positive (FP)0
False Negative (FN)0
True Positive (TP)5
Precision: 100%Recall: 100%
Threshold T = 0.50
x = 0 (Small / Low)Input Feature Value (x)x = 10 (Large / High)
Negative (Class 0)Positive (Class 1)
Red ring = classification error with current threshold
Why the threshold matters: In clinical diagnosis (e.g. cancer detection), missing a true disease (False Negative) is disastrous. By dragging the threshold slider down from 0.50 to 0.25, the model flags more patients for screening, driving Recall up to 100% at the price of a few harmless False Alarms. In spam filtering, where false alarms annoy users, we move the threshold up to 0.80 to ensure high Precision.

Worked Example of Sigmoid Function

Suppose: z = 2

σ(2) = 1 / (1 + e⁻²)

(Approx: e⁻² ≈ 0.135)

Step 1: e⁻² ≈ 0.1353

Step 2: 1 + 0.1353 = 1.1353

Step 3: 1 / 1.1353 ≈ 0.881

σ(2) ≈ 0.881

Meaning: about 88.1% model-estimated probability of Class 1


Probability Threshold & Decision Boundary

A predicted probability can be converted into a class label using a chosen threshold. A threshold of 0.5 is a common starting point for binary classification, but it is not automatically the best threshold. The decision boundary is where the model switches from one class decision to the other.

Threshold Logic

Probability ≥ 0.5 → Class 1
Probability < 0.5 → Class 0
0 (Class 0)
1 (Class 1)
0.5

Same probability, different threshold

Probability = 0.72
Threshold = 0.50 → Class 1
Probability = 0.72
Threshold = 0.80 → Class 0

Simple Decision Boundary

Class 0Class 1Decision boundary

In the original feature space, standard Logistic Regression creates a linear boundary. Nonlinear feature engineering can make the resulting boundary more flexible.


Cost Function & Gradient Descent

Log Loss Formula

Unlike Linear Regression, Logistic Regression uses Log Loss.

J(θ) = -1/m ∑ [y*log(ŷ) + (1-y)*log(1-ŷ)]
  • y: Actual label (0 or 1)
  • ŷ: Predicted probability of Class 1
  • m: Number of samples

One-sample example

Actual label: y = 1

Predicted probability: ŷ = 0.8

Loss = -log(0.8)

Loss ≈ 0.223

A confident correct prediction gets a small loss. If the model predicted 0.1 for this positive example, the loss would be about 2.303.

Why Log Loss Fits Logistic Regression

Log Loss matches the probabilistic model used by binary Logistic Regression. It strongly penalizes confident wrong predictions.

  • Uses the predicted probability directly
  • Rewards confident correct predictions
  • Penalizes confident wrong predictions heavily

MSE can be computed for probabilities, but it is not the standard training objective for ordinary Logistic Regression.

Gradient Descent Intuition

One way to understand optimization is to repeatedly move the coefficients in a direction that reduces Log Loss. Practical libraries may use gradient-based, Newton-style, or coordinate-based solvers depending on the settings.

θ = θ - α(∂J / ∂θ)

θ = coefficients, α = learning rate, J = cost function

Learning Workflow
Initialize Weights
↓
Calculate Predictions
↓
Compute Error
↓
Update Weights
↓
Repeat Until Convergence

Odds, Logit Function & Scaling

Odds Definition

Logistic Regression uses odds internally.

Odds = P / (1 - P)

Worked Example:

Suppose P = 0.8

Odds = 0.8 / (1 - 0.8) = 0.8 / 0.2

Odds = 4

Meaning: the positive outcome has odds of 4 to 1 against the negative outcome.

Logit Function

The logit converts a probability into log-odds. Logistic Regression models these log-odds as a linear combination of the features.

Logit = log( P / (1 - P) )
Why Logistic Regression is called a linear model:the log-odds are linear in the input features, so the standard decision boundary is linear in that feature space.

Feature Scaling

Feature scaling is often helpful when numerical features have very different units. It can make optimization more stable for some solvers and makes regularization treat coefficient scales more fairly.

X_scaled = (X - μ) / σ

Example:

X = 100, Mean(μ) = 80, StdDev(σ) = 10

Step 1: 100 - 80 = 20

Step 2: 20 / 10 = 2

X_scaled = 2


Evaluation Metrics

Confusion Matrix

Predicted
YESNO
Actual YESTPFN
Actual NOFPTN

Core Formulae

  • AccuracyAcc = (TP+TN)/(TP+TN+FP+FN)
  • PrecisionPrec = TP / (TP+FP)
  • RecallRecall = TP / (TP+FN)
  • F1 ScoreF1 = 2*(Prec*Rec)/(Prec+Rec)

Metric Example with Small Numbers

Suppose TP = 8, TN = 7, FP = 1, FN = 2.

Accuracy: (8+7)/(8+7+1+2) = 15/18 ≈ 83.3%
Precision: 8/(8+1) = 8/9 ≈ 88.9%
Recall: 8/(8+2) = 8/10 = 80%
F1: 2×(0.889×0.80)/(0.889+0.80) ≈ 84.2%

ROC Curve

ROC Curve measures classification performance across various thresholds.

It plots True Positive Rate vs False Positive Rate.


Comparisons & Applications

Logistic vs Linear Regression

OutputProbabilityContinuous
FunctionSigmoidLinear
Cost FxLog LossMSE

Logistic vs Decision Tree

BoundaryLinear in chosen feature spacePiecewise, axis-aligned splits
ComplexityUsually lowerDepends on tree depth
Overfit RiskDepends on regularizationCan be high for deep trees

Industry Applications

Healthcare

  • Disease Prediction
  • Cancer Detection
  • Medical Risk Analysis

Finance

  • Credit Scoring
  • Fraud Detection
  • Loan Approval

Marketing

  • Customer Conversion
  • Churn Prediction
  • Ad Analytics

Python Implementation (Practical Guide)

Here is a complete, beginner-friendly step-by-step implementation of Logistic Regression using Python and Scikit-Learn's Breast Cancer Wisconsin dataset. It is a naturally binary classification dataset, so we do not need to manufacture labels from a regression target.

Machine Learning Pipeline Workflow

Load Dataset→Preprocess Data→Split Dataset→Feature Scaling→Train Model→Make Predictions→Evaluate Model

Python ML Libraries

PYTHON ML LIBRARIES
NumPy
Pandas
Scikit-Learn
• LogisticRegression
• StandardScaler
• Train/Test Split
• Metrics

Natural Binary Labels

This dataset already contains two target classes, so the example stays a genuine classification problem.

0 → Malignant
1 → Benign

Educational dataset only; this tutorial is not a clinical diagnostic tool.

python

Interactive: Train Logistic Regression in Python

Adjust test set split size and max iterations, then execute scikit-learn's LogisticRegression model live.

Live Hyperparameters (Tweak & Re-run)
0.2
0.10.4

Proportion of the dataset held out for unbiased evaluation.

1000
1001000

Maximum solver steps for lbfgs optimization to reach convergence.

1from sklearn.datasets import load_breast_cancer
2from sklearn.model_selection import train_test_split
3from sklearn.preprocessing import StandardScaler
4from sklearn.linear_model import LogisticRegression
5from sklearn.metrics import accuracy_score, confusion_matrix, classification_report, roc_auc_score
6
7# Step 1: Load Dataset
8data = load_breast_cancer()
9X, y = data.data, data.target
10
11# Step 2: Split Before Scaling
12test_size = 0.2
13X_train, X_test, y_train, y_test = train_test_split(
14 X, y, test_size=0.2
15)
16
17# Step 3: Standardize Features
18scaler = StandardScaler()
19X_train_scaled = scaler.fit_transform(X_train)
20X_test_scaled = scaler.transform(X_test)
21
22# Step 4: Train Logistic Regression
23max_iter = 1000
24model = LogisticRegression(max_iter=1000
25model.fit(X_train_scaled, y_train)
26
27# Step 5: Predict & Evaluate
28y_pred = model.predict(X_test_scaled)
29y_prob = model.predict_proba(X_test_scaled)[:, 1]
30
31acc = accuracy_score(y_test, y_pred)
32auc = roc_auc_score(y_test, y_prob)
33
34print(f"Accuracy: {acc:.4f}")
35print("Confusion Matrix:")
36print(confusion_matrix(y_test, y_pred))
37print(f"ROC AUC Score: {auc:.4f}")
38print("\nClassification Report:")
39print(classification_report(y_test, y_pred, target_names=data.target_names))
Click "Run Code" above to execute this script in the sandbox and inspect live outputs.

Expected Output

Accuracy: 0.9824561403508771

[[41  1]
[ 1 71]]

malignant  precision 0.98  recall 0.98  f1-score 0.98
benign     precision 0.99  recall 0.99  f1-score 0.99

ROC AUC: 0.9953703703703703

Example output from the fixed split shown above. Small numerical differences can occur across library versions. A strong score on this teaching dataset should not be interpreted as proof of clinical readiness.


Best Practices & Common Mistakes

Common Mistakes

  • Ignoring feature scaling: Can slow or destabilize optimization when feature scales differ greatly.
  • Using wrong threshold: Can create the wrong trade-off between false positives and false negatives.
  • Imbalanced data: Results in misleading aggregate accuracy scores.

Best Practices

  • Scale numerical features when feature scales differ substantially or the chosen solver/regularization benefits from it.
  • Use cross-validation.
  • Tune threshold carefully based on business context.
  • Handle class imbalance thoughtfully; consider class weights, resampling, and suitable metrics rather than applying one technique automatically.
  • Evaluate multiple metrics (F1, Precision, Recall).
  • Use Regularization (L1/L2) if needed.

Regularization in Scikit-Learn Logistic Regression

Scikit-Learn's LogisticRegression applies regularization by default. The parameter Ccontrols its strength inversely.

Smaller C → stronger regularization
Larger C → weaker regularization

The available L1, L2, or Elastic-Net choices depend on the solver. Choose settings with validation rather than assuming one value is always best.

Common Questions

Why is it called regression if it performs classification?
Because it models the log-odds as a regression-like linear equation, then converts the result to a probability and class decision.
Is 0.5 always the best threshold?
No. The threshold should reflect validation results and the real cost of false positives versus false negatives.
Can Logistic Regression handle more than two classes?
Yes. Multinomial logistic regression can handle multiple unordered classes. Ordered outcomes require specialized ordinal models.
What should I learn next?
Continue with Decision Trees, or revisit Confusion Matrix and ROC-AUC for evaluation.

Final Summary

Logistic Regression is a classification algorithm in Machine Learning. It works by taking a linear combination of inputs, passing them through a Sigmoid Function, outputting a probability, and assigning a class based on a threshold.

Its major strengths include simplicity, computational efficiency, and coefficient-based interpretability. It can provide useful estimated probabilities, but those probabilities should still be evaluated for calibration and used with a threshold that fits the problem. It is a strong baseline for many binary and multiclass classification tasks.

Most Important Insight to Remember:

"The key idea is simple: Logistic Regression turns a linear score into an estimated probability, then uses a decision rule to choose a class."

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Logistic Regression"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Summary / Key Takeaways

  • Binary logistic regression maps a linear score through sigmoid to a probability.
  • A threshold converts probability to a class and need not be 0.5.
  • Coefficients act on log-odds; exponentiation gives odds ratios under the model.
  • Cross-entropy penalizes confident wrong probabilities strongly.
  • Scaling, regularization, imbalance, and correlated inputs affect fitting.
  • Validate probabilities and threshold-dependent metrics on unseen data.

Knowledge Check

Progress: 0/4

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 4
Why does logistic regression use the sigmoid function rather than a linear output?
Question 2 of 4
Logistic regression predicts default probability 0.92 for a loan applicant. At what threshold would you NOT flag this applicant?
Question 3 of 4
Logistic regression performs poorly and residual analysis confirms the log-odds relationship is non-linear. What is the appropriate fix?
Question 4 of 4
Your classifier achieves precision=0.41, recall=0.87 for fraud. A risk manager says precision is unacceptably low. What options do you have?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Why does logistic regression use the sigmoid function rather than a linear output?▼

Correct Answer: A linear combination of features can produce any real number, but probabilities must be in (0,1). The sigmoid maps any real input to (0,1), making the output interpretable as a class probability. Without it, the model could predict probabilities of -3.7 or 12.4

This is the fundamental motivation for the sigmoid. The log-odds (logit) is linear: log(p/(1-p)) = Xw. Taking the inverse logit gives the sigmoid. The model is linear in log-odds space but produces probabilities through the sigmoid transformation.

2Logistic regression predicts default probability 0.92 for a loan applicant. At what threshold would you NOT flag this applicant?▼

Correct Answer: Only a threshold above 0.92 would not flag this applicant. At any threshold ≤0.92 (including the standard 0.5), they are predicted as positive. Moving the threshold above 0.92 changes the prediction — but this would miss almost all defaults

The threshold determines which probabilities become positive predictions. With p=0.92: threshold 0.5→positive, threshold 0.8→positive, threshold 0.95→negative. Raising threshold above 0.92 changes this specific prediction but at the cost of missing other likely defaults.

3Logistic regression performs poorly and residual analysis confirms the log-odds relationship is non-linear. What is the appropriate fix?▼

Correct Answer: Add polynomial features or interaction terms to capture non-linearity within the framework, or switch to a non-linear model (Random Forest, XGBoost) that learns complex boundaries without manual feature engineering

Logistic regression is a linear classifier — its decision boundary is always a hyperplane. Non-linear boundaries require either feature engineering (explicit non-linear features) or switching to inherently non-linear models.

4Your classifier achieves precision=0.41, recall=0.87 for fraud. A risk manager says precision is unacceptably low. What options do you have?▼

Correct Answer: Raise the classification threshold above 0.5 — predict fraud only when the model is more confident. This reduces false positives (higher precision) but also reduces true positives (lower recall). The business must decide which error is more costly

Precision and recall are properties of the model at a specific threshold, not fixed model properties. Raising the threshold increases precision at the cost of recall. The business must decide the acceptable operating point.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next