Linear vs. Logistic Regression: The Complete Guide
Linear regression and logistic regression are two foundational algorithms in supervised machine learning. Although they share similar mathematical foundations, they solve fundamentally different problems: linear regression predicts continuous quantities, while logistic regression estimates probabilities and predicts discrete classes.
Confusing their mechanics or applying linear regression directly to classification tasks is a common beginner mistake.
Understanding how these algorithms work, how their mathematical formulations differ, and when to use each one is essential for building effective machine learning models.
Let's explore both algorithms, their loss functions, assumptions, applications, and practical Python implementations.
1. Linear Regression: Predicting Continuous Quantities
Linear regression is a supervised machine learning algorithm used to predict a continuous target variable based on one or more independent input features.
It attempts to establish a linear relationship between input variables (\(X\)) and an output variable (\(y\)).
Mathematical Formulation
For a dataset containing one input feature, simple linear regression can be represented as:
\[ \hat{y}=w_0+w_1x \]
Where:
- \(\hat{y}\) = Predicted output.
- \(w_0\) = Intercept or bias.
- \(w_1\) = Coefficient or slope.
- \(x\) = Input feature.
For multiple input features, multiple linear regression is represented as:
\[ \hat{y}=w_0+w_1x_1+w_2x_2+\dots+w_px_p \]
In vector notation:
\[ \hat{y}=w_0+\mathbf{w}^T\mathbf{x} \]
Key characteristics:
- Output: Any continuous real number.
- Objective: Minimize the difference between actual and predicted values.
- Model: A straight line, plane, or hyperplane in the feature space.
- Learning: Ordinary Least Squares (OLS) or optimization methods such as gradient descent.
Example: House Price Prediction
Suppose you want to predict house prices using the size of a property.
| House Size (sq. ft.) | Actual Price (₹ Lakhs) |
|---|---|
| 500 | 25 |
| 800 | 40 |
| 1,000 | 50 |
| 1,200 | 60 |
| 1,500 | 75 |
A linear regression model might learn:
\[ Price=0.05\times Size \]
For a house measuring 1,100 square feet:
\[ Price=0.05\times1100 \]
\[ \boxed{Price=₹55\text{ Lakhs}} \]
The model predicts a continuous numerical value rather than assigning the house to a category.
1.1 Loss Function: Mean Squared Error (MSE)
Linear regression commonly uses Mean Squared Error to measure the difference between actual and predicted values.
\[ MSE=\frac{1}{n}\sum_{i=1}^{n}(y_i-\hat{y}_i)^2 \]
Where:
- \(n\) = Number of observations.
- \(y_i\) = Actual value.
- \(\hat{y}_i\) = Predicted value.
- \(y_i-\hat{y}_i\) = Residual or prediction error.
The objective is to find model parameters that minimize the MSE.
\[ J(\mathbf{w})=\frac{1}{n}\sum_{i=1}^{n} (y_i-\hat{y}_i)^2 \]
Squaring the residuals has two important effects:
- Positive and negative errors cannot cancel each other out.
- Larger errors receive a greater penalty.
Example
Suppose the actual house price is ₹50 Lakhs.
| Actual Price | Predicted Price | Squared Error |
|---|---|---|
| 50 | 45 | 25 |
| 50 | 48 | 4 |
| 50 | 55 | 25 |
\[ MSE=\frac{25+4+25}{3} \]
\[ \boxed{MSE=18} \]
A lower MSE generally indicates better predictions on the evaluated dataset.
1.2 How Does Linear Regression Learn?
Linear regression adjusts its coefficients to minimize prediction errors.
Two common approaches are:
1. Ordinary Least Squares (OLS)
OLS estimates coefficients by minimizing the sum of squared residuals.
For a suitable full-rank design matrix, its solution can be expressed as:
\[ \mathbf{w}=(X^TX)^{-1}X^Ty \]
This expression assumes the matrix inverse exists. In other cases, a pseudoinverse or numerical least-squares solver can be used.
2. Gradient Descent
Gradient descent iteratively updates model parameters to reduce the loss.
\[ w_j:=w_j-\alpha\frac{\partial J}{\partial w_j} \]
Where:
- \(w_j\) = Model parameter.
- \(\alpha\) = Learning rate.
- \(J\) = Loss function.
Gradient descent is useful for large datasets and optimization problems where a direct solution is inconvenient.
Important Mathematical Property
The ordinary least-squares objective is convex. Therefore, it does not contain multiple local minima.
However, it is strictly convex and has a unique coefficient solution only under suitable conditions, such as a full-column-rank design matrix.
1.3 Assumptions of Linear Regression
Traditional linear regression relies on several assumptions, particularly when statistical inference is important.
- Linearity: The conditional mean of the target is linear in the model parameters.
- Independence: Observations or errors should be independent under the assumed sampling structure.
- Homoscedasticity: Error variance should be approximately constant across fitted values.
- Normality of Errors: Normally distributed errors are useful for exact small-sample statistical inference, although they are not required for calculating OLS predictions.
- Low Multicollinearity: Strong relationships between predictors can make coefficient estimates unstable.
- Exogeneity: Predictors should not be systematically correlated with the error term for standard coefficient interpretation and unbiasedness.
Violating these assumptions can affect model interpretation, statistical inference, or predictive performance.
1.4 Common Applications of Linear Regression
- Real estate price estimation.
- Sales and revenue forecasting.
- Demand prediction.
- Temperature and energy consumption forecasting.
- Salary prediction.
- Estimating product demand based on advertising expenditure.
2. Logistic Regression: Predicting Probabilities and Classes
Despite containing the word "regression" in its name, logistic regression is primarily used for classification problems.
It estimates the probability that an observation belongs to a particular class.
For binary classification:
\[ y\in\{0,1\} \]
Where:
- 0 = Negative class.
- 1 = Positive class.
Unlike linear regression, logistic regression does not directly predict unrestricted continuous values as its final output. It transforms a linear score into a probability.
2.1 Why Do We Need Logistic Regression?
Imagine predicting whether a customer will purchase a product.
The target variable contains only two possible values:
0 = Customer will not purchase
1 = Customer will purchase
If we apply ordinary linear regression directly to this binary target, the model may produce outputs such as:
-0.35
0.45
0.82
1.40
These values are not all valid probabilities because probabilities must lie between 0 and 1.
Logistic regression solves this problem using the sigmoid function.
2.2 The Sigmoid Function
The sigmoid function transforms a real-valued input into a number strictly between 0 and 1.
\[ \sigma(z)=\frac{1}{1+e^{-z}} \]
Where:
\[ z=w_0+w_1x_1+w_2x_2+\dots+w_px_p \]
The predicted positive-class probability becomes:
\[ \hat{p}=P(Y=1\mid X)= \frac{1}{1+e^{-z}} \]
Interpretation:
- If \(z\) is strongly positive, the predicted probability approaches 1.
- If \(z\) is strongly negative, the predicted probability approaches 0.
- If \(z=0\), the predicted probability equals 0.5.
Example
Suppose a logistic regression model produces the following linear score:
\[ z=2 \]
Applying the sigmoid function:
\[ P(Y=1\mid X)=\frac{1}{1+e^{-2}} \]
\[ \boxed{P(Y=1\mid X)\approx0.881} \]
The model estimates an 88.1% probability of belonging to the positive class.
2.3 Understanding the Decision Threshold
Logistic regression produces probabilities, but classification requires converting those probabilities into class labels.
A common default threshold is 0.5.
\[ \hat{y}= \begin{cases} 1 & \text{if } \hat{p}\geq0.5\\ 0 & \text{if } \hat{p}<0.5 \end{cases} \]
For example:
| Predicted Probability | Threshold | Predicted Class |
|---|---|---|
| 0.95 | 0.50 | 1 |
| 0.82 | 0.50 | 1 |
| 0.60 | 0.50 | 1 |
| 0.40 | 0.50 | 0 |
| 0.15 | 0.50 | 0 |
The threshold can be adjusted depending on the problem.
For example, a fraud detection system may use a lower threshold to identify more potentially fraudulent transactions, even if this increases false positives.
The best threshold depends on the cost of different classification errors.
2.4 Log-Odds Interpretation
One of the most important mathematical concepts in logistic regression is the relationship between probability and odds.
The odds of a positive outcome are:
\[ Odds=\frac{p}{1-p} \]
Taking the natural logarithm gives the log-odds, also called the logit:
\[ \log\left(\frac{p}{1-p}\right) =w_0+w_1x_1+\dots+w_px_p \]
This is the key mathematical idea behind logistic regression.
It models the log-odds as a linear combination of input features.
How to interpret a coefficient:
If a feature coefficient is \(w_j\), increasing that feature by one unit while holding other features constant changes the log-odds by \(w_j\).
Its corresponding odds are multiplied by:
\[ e^{w_j} \]
For example, if:
\[ w_j=0.7 \]
Then:
\[ e^{0.7}\approx2.01 \]
The odds of a positive outcome are approximately doubled for a one-unit increase in that feature, assuming the other features remain unchanged.
This does not mean the probability itself doubles.
2.5 Loss Function: Log Loss (Binary Cross-Entropy)
Unlike standard linear regression, logistic regression commonly uses Log Loss, also called Binary Cross-Entropy, for maximum-likelihood training.
\[ J(\mathbf{w})= -\frac{1}{n}\sum_{i=1}^{n} \left[ y_i\log(\hat{p}_i) +(1-y_i)\log(1-\hat{p}_i) \right] \]
Where:
- \(y_i\) = Actual binary label.
- \(\hat{p}_i\) = Predicted positive-class probability.
- \(n\) = Number of observations.
Log Loss penalizes incorrect and overconfident probability predictions.
Example
Suppose the actual class is positive:
\[ y=1 \]
Consider two predictions:
| Actual Class | Predicted Probability | Approximate Log Loss |
|---|---|---|
| 1 | 0.90 | 0.105 |
| 1 | 0.20 | 1.609 |
The second prediction receives a much larger penalty because the model assigned a low probability to the actual positive outcome.
For logistic regression with the standard binary cross-entropy objective, the loss is convex in the coefficients, although it may not have a unique finite minimizer in every dataset configuration.
2.6 Types of Logistic Regression
Logistic regression can be extended to different classification problems.
1. Binary Logistic Regression
Used when the target contains two classes.
Examples:
- Spam vs. Not Spam.
- Fraud vs. Not Fraud.
- Purchased vs. Not Purchased.
- Disease vs. No Disease.
2. Multinomial Logistic Regression
Used when the target contains three or more mutually exclusive classes.
Examples:
- Classifying an image as Cat, Dog, or Bird.
- Predicting a product category.
- Classifying customer feedback as Positive, Neutral, or Negative.
It commonly uses the Softmax function:
\[ P(Y=k\mid X)= \frac{e^{z_k}}{\sum_{j=1}^{K}e^{z_j}} \]
Where \(K\) is the number of classes.
3. Ordinal Logistic Regression
Used when classes have a meaningful order.
Examples:
- Customer satisfaction: Poor, Average, Good, Excellent.
- Education levels.
- Risk categories: Low, Medium, High.
Ordinal logistic regression models ordered outcomes using cumulative probabilities and threshold parameters.
3. Linear Regression vs. Logistic Regression: Key Differences
Although both algorithms use a linear combination of input features, their outputs, objectives, and applications differ significantly.
| Feature | Linear Regression | Logistic Regression |
|---|---|---|
| Main Purpose | Predict continuous values | Predict class probabilities |
| Problem Type | Regression | Classification |
| Target Variable | Continuous | Categorical |
| Output | Unrestricted real number | Probability between 0 and 1 |
| Core Function | Linear equation | Linear score + sigmoid or softmax |
| Common Loss | MSE | Log Loss |
| Optimization | OLS or gradient-based methods | Maximum likelihood / gradient-based methods |
| Evaluation | MAE, MSE, RMSE, R² | Precision, Recall, F1, ROC-AUC, Log Loss |
| Typical Examples | House prices, revenue | Fraud, spam, customer churn |
| Decision Threshold | Not normally required | Required to convert probabilities into classes |
The most important distinction:
Linear regression predicts how much or how many.
Logistic regression predicts which class and estimates the probability of belonging to that class.
4. Can Linear Regression Be Used for Classification?
Technically, a linear regression model can be applied to binary classification by setting a threshold on its output.
However, this is generally not the preferred approach.
Consider a binary target:
0 = Not Purchased
1 = Purchased
A linear regression model might predict:
-0.20
0.35
0.70
1.25
You could apply a threshold of 0.5 to convert these values into classes.
However, several problems arise:
- Predictions can fall below 0 or above 1.
- The model is not optimized using the standard Bernoulli likelihood for classification.
- Its error assumptions are not well suited to binary outcomes.
- Its probability estimates may be unreliable.
- It may produce a poorly suited decision boundary.
Logistic regression is specifically designed for binary probability modeling and is generally a more appropriate starting point.
5. Regularization in Linear and Logistic Regression
Both linear and logistic regression can overfit when the model contains too many features, noisy predictors, or highly correlated variables.
Regularization adds a penalty to the objective function to control model complexity.
5.1 L1 Regularization (Lasso)
L1 regularization adds the absolute values of coefficients to the loss.
\[ J=Loss+\lambda\sum_{j=1}^{p}|w_j| \]
It can shrink some coefficients exactly to zero, effectively performing feature selection.
5.2 L2 Regularization (Ridge)
L2 regularization adds the squared values of coefficients to the loss.
\[ J=Loss+\lambda\sum_{j=1}^{p}w_j^2 \]
It shrinks coefficient values toward zero but generally does not make them exactly zero.
5.3 Elastic Net
Elastic Net combines L1 and L2 regularization.
\[ J=Loss+ \lambda_1\sum_{j=1}^{p}|w_j| +\lambda_2\sum_{j=1}^{p}w_j^2 \]
It can provide a balance between coefficient shrinkage and feature selection.
These regularization techniques can be applied to both linear and logistic regression, although the exact parameterization differs across libraries.
6. Practical Implementation Using Python and Scikit-Learn
Let's implement both algorithms using Python and Scikit-learn.
We will build:
- A Linear Regression model to predict continuous values.
- A Logistic Regression model to predict binary classes.
6.1 Linear Regression Implementation
Step 1: Import Libraries
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import (
mean_absolute_error,
mean_squared_error,
r2_score
)
Step 2: Create a Dataset
X = np.array([
[500],
[600],
[700],
[800],
[900],
[1000],
[1100],
[1200],
[1300],
[1400]
])
y = np.array([
25, 30, 35, 40, 45,
50, 55, 60, 65, 70
])
Here, the input represents house size and the target represents house price in lakhs.
Step 3: Split the Dataset
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.20,
random_state=42
)
Step 4: Train the Model
model = LinearRegression()
model.fit(X_train, y_train)
Step 5: Make Predictions
predictions = model.predict(X_test)
print("Predicted Prices:", predictions)
print("Actual Prices:", y_test)
Step 6: Evaluate the Model
print("MAE:", mean_absolute_error(y_test, predictions))
print("MSE:", mean_squared_error(y_test, predictions))
print("RMSE:", np.sqrt(
mean_squared_error(y_test, predictions)
))
print("R2 Score:", r2_score(y_test, predictions))
Step 7: Predict a New House Price
new_house = np.array([[1500]])
predicted_price = model.predict(new_house)
print("Predicted House Price:", predicted_price[0])
The model predicts a continuous numerical value.
6.2 Logistic Regression Implementation
Step 1: Import Libraries
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
accuracy_score,
precision_score,
recall_score,
f1_score,
classification_report,
confusion_matrix
)
Step 2: Generate a Classification Dataset
X, y = make_classification(
n_samples=1000,
n_features=5,
n_informative=3,
n_redundant=1,
random_state=42
)
The dataset contains input features and a binary target.
Step 3: Split the Dataset
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.20,
stratify=y,
random_state=42
)
Stratification helps preserve approximately the same class proportions in the training and test datasets.
Step 4: Train the Model
model = make_pipeline(
StandardScaler(),
LogisticRegression(max_iter=1000)
)
model.fit(X_train, y_train)
Feature scaling is included in the pipeline to improve optimization and ensure that preprocessing is learned from the training data.
Step 5: Predict Classes and Probabilities
predictions = model.predict(X_test)
probabilities = model.predict_proba(X_test)
print("Predicted Classes:", predictions[:10])
print("Predicted Probabilities:", probabilities[:10])
predict() returns predicted class labels, while predict_proba() returns class probabilities.
Step 6: Evaluate the Model
print("Accuracy:", accuracy_score(y_test, predictions))
print("Precision:", precision_score(y_test, predictions))
print("Recall:", recall_score(y_test, predictions))
print("F1 Score:", f1_score(y_test, predictions))
print("Confusion Matrix:")
print(confusion_matrix(y_test, predictions))
print(classification_report(y_test, predictions))
These metrics help evaluate classification performance from different perspectives.
7. Evaluation Metrics: Which Ones Should You Use?
The two algorithms require different evaluation metrics because they solve different prediction problems.
Linear Regression Metrics
| Metric | Purpose |
|---|---|
| MAE | Measures average absolute prediction error |
| MSE | Penalizes larger prediction errors more heavily |
| RMSE | Measures error in the original target units |
| R² | Measures performance relative to a mean-prediction baseline |
For example, when predicting house prices, RMSE can tell you how large prediction errors are in lakhs.
Logistic Regression Metrics
| Metric | Purpose |
|---|---|
| Accuracy | Measures the fraction of correct predictions |
| Precision | Measures the reliability of positive predictions |
| Recall | Measures how many actual positives are identified |
| F1-Score | Balances precision and recall |
| ROC-AUC | Measures ranking ability across classification thresholds |
| Log Loss | Evaluates the quality of predicted probabilities |
For imbalanced datasets, accuracy alone can be misleading. Precision, recall, F1, and Precision-Recall AUC may provide more useful information.
8. Real-World Applications
Linear Regression Applications
1. Real Estate
Predict property prices using area, location-related features, number of rooms, and property age.
2. Sales Forecasting
Estimate future sales using advertising expenditure, historical sales, and seasonal variables.
3. Healthcare
Estimate continuous measurements such as hospital stay duration or resource consumption.
4. Energy Consumption
Predict electricity demand using temperature, time, and historical consumption.
Logistic Regression Applications
1. Banking and Fraud Detection
Predict whether a transaction is potentially fraudulent.
2. Email Spam Detection
Classify incoming emails as spam or legitimate.
3. Customer Churn Prediction
Estimate whether a customer is likely to stop using a service.
4. Healthcare Classification
Estimate the probability of a particular medical outcome to support further clinical assessment.
5. Marketing
Predict whether a customer is likely to click an advertisement or purchase a product.
9. Common Mistakes Beginners Should Avoid
- Using Linear Regression for Classification: Its unrestricted outputs are not naturally suitable as class probabilities.
- Assuming Logistic Regression Is a Regression Algorithm: Despite its name, it is commonly used for classification.
- Confusing Probability with Class Labels: A predicted probability of 0.80 is not the same as a predicted class of 1.
- Always Using a 0.5 Threshold: The best threshold depends on the relative costs of false positives and false negatives.
- Ignoring Feature Scaling: Scaling is particularly important for many regularized and gradient-based implementations of logistic regression.
- Ignoring Multicollinearity: Highly correlated features can make coefficient interpretation unstable.
- Evaluating Only with Accuracy: Accuracy can hide poor minority-class performance.
- Assuming Linear Relationships Are Always Appropriate: Both algorithms use linear relationships in their transformed modeling space. Nonlinear patterns may require feature engineering, transformations, or more flexible models.
- Ignoring Outliers in Linear Regression: Large residuals can strongly influence ordinary least-squares estimates.
- Assuming Logistic Regression Guarantees Calibrated Probabilities: Probability quality should still be evaluated on representative held-out data.
10. How to Choose Between Linear and Logistic Regression
The simplest way to select an algorithm is to examine the target variable.
| Your Prediction Goal | Recommended Algorithm | Example |
|---|---|---|
| Predict a numerical price | Linear Regression | House price prediction |
| Predict monthly revenue | Linear Regression | Sales forecasting |
| Predict temperature | Linear Regression | Weather-related estimation |
| Predict Yes or No | Logistic Regression | Customer purchase prediction |
| Predict Fraud or Not Fraud | Logistic Regression | Banking |
| Predict Spam or Not Spam | Logistic Regression | Email filtering |
| Predict one of multiple categories | Multinomial Logistic Regression | Image classification |
Decision rule:
- If the target is continuous, start by considering regression algorithms such as Linear Regression.
- If the target represents categories, consider classification algorithms such as Logistic Regression.
The final algorithm should also be selected based on data characteristics, assumptions, validation results, and the business problem.
Conclusion
Linear regression and logistic regression are foundational supervised machine learning algorithms, but they solve different prediction problems.
Linear regression estimates continuous numerical values by modeling a linear relationship between input features and the target variable. It commonly minimizes Mean Squared Error using Ordinary Least Squares or optimization methods such as gradient descent.
Logistic regression estimates class probabilities by applying the sigmoid function to a linear combination of input features. It commonly uses Log Loss to learn parameters and applies a decision threshold to convert probabilities into class labels.
The key difference is simple:
- Linear Regression: Predicts how much or how many.
- Logistic Regression: Predicts which class and estimates its probability.
Understanding these differences provides a strong foundation for learning more advanced supervised machine learning algorithms, including Decision Trees, Random Forests, Support Vector Machines, and Gradient Boosting.