Introduction
Linear regression is one of the most widely used algorithms in statistics and machine learning. It helps us understand the relationship between variables and predict continuous numerical values.
For example, we can use linear regression to predict a student's marks based on study hours, estimate house prices based on area, or analyze how a numerical feature relates to a target variable.
In this guide, we will explore the mathematical foundation of linear regression, understand how it works, and implement it using Python and a real dataset.
1. What is Linear Regression?
Linear regression is a supervised machine learning algorithm used to predict a continuous numerical value.
It learns the relationship between one or more independent variables (input features) and a dependent variable (target) by fitting a linear equation to the data.
There are two common types:
- Simple linear regression: Uses one input feature to predict the output.
- Multiple linear regression: Uses two or more input features to predict the output.
2. Mathematical Formula
The equation for simple linear regression is:
ŷ = β₀ + β₁x
Where:
- ŷ = Predicted output.
- x = Independent variable or input feature.
- β₀ = Intercept, the predicted value when x = 0.
- β₁ = Slope, the change in the predicted output for a one-unit increase in x.
For multiple linear regression, the equation becomes:
ŷ = β₀ + β₁x₁ + β₂x₂ + ... + βₚxₚ
Each coefficient represents the contribution of its corresponding feature to the prediction, holding the other features constant.
Example: Predicting Student Marks
Suppose we want to predict a student's marks based on the number of hours studied.
The regression equation is:
ŷ = 20 + 10x
Here, the intercept is 20 and the slope is 10. This means that for every additional hour of study, the predicted score increases by 10 marks.
If the student studies for 5 hours:
ŷ = 20 + 10 × 5
ŷ = 70
Therefore, the predicted score is 70 marks.
This is a hypothetical example. In a real dataset, the model learns the intercept and slope from the training data.
3. How Does Linear Regression Work?
A linear regression model finds the line that best represents the relationship between the input and output variables.
The difference between an actual value and its predicted value is called a residual.
Residual Formula
eᵢ = yᵢ − ŷᵢ
Where:
- eᵢ = Residual for observation i.
- yᵢ = Actual value.
- ŷᵢ = Predicted value.
A common method called Ordinary Least Squares (OLS) estimates the coefficients by minimizing the sum of squared residuals.
Sum of Squared Errors (SSE)
SSE = Σ(yᵢ − ŷᵢ)²
The summation includes all observations from i = 1 to n.
The objective is to find the coefficients that produce the smallest possible sum of squared errors on the training data.
For simple linear regression, the least-squares estimates can be calculated using the following formulas.
Slope:
β₁ = Σ[(xᵢ − x̄)(yᵢ − ȳ)] / Σ[(xᵢ − x̄)²]
Intercept:
β₀ = ȳ − β₁x̄
Where:
- x̄ = Mean of the input values.
- ȳ = Mean of the output values.
- Σ = Sum of the values over all observations.
These equations explain how the model learns its slope and intercept from the data.
4. Practical Implementation Using Python
In this example, we will use the diabetes dataset available in scikit-learn.
The dataset contains 442 observations, 10 numerical features, and a target representing disease progression one year after baseline.
For simplicity, we will use only the BMI feature to demonstrate simple linear regression.
Step 1: Install the Required Libraries
Run the following command in your terminal:
pip install numpy matplotlib scikit-learn
Step 2: Import Libraries and Load the Dataset
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score
data = load_diabetes(as_frame=True)
X = data.data[["bmi"]]
y = data.target
The input X contains the scaled BMI feature, while y contains the disease progression target.
Step 3: Split the Dataset
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
We use 80% of the data for training and 20% for testing.
The fixed random state ensures that the same train-test split can be reproduced.
Step 4: Train the Model
model = LinearRegression()
model.fit(X_train, y_train)
print("Intercept:", model.intercept_)
print("Slope:", model.coef_[0])
The model learns the intercept and slope from the training data.
Step 5: Make Predictions
y_pred = model.predict(X_test)
print("First five predictions:")
print(np.round(y_pred[:5], 2))
These predictions represent estimated disease progression values for the test samples.
Step 6: Evaluate the Model
mae = mean_absolute_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f"MAE: {mae:.2f}")
print(f"R² score: {r2:.3f}")
Two common evaluation metrics are Mean Absolute Error (MAE) and the coefficient of determination (R²).
Mean Absolute Error (MAE)
MAE = (1/n) × Σ|yᵢ − ŷᵢ|
MAE measures the average absolute difference between actual and predicted values.
A lower MAE indicates smaller prediction errors.
R-squared (R²)
R² = 1 − [Σ(yᵢ − ŷᵢ)² / Σ(yᵢ − ȳ)²]
R² measures how well the model explains variation in the target compared with a baseline that always predicts the mean.
- An R² of 1 indicates perfect predictions.
- An R² of 0 indicates performance equal to the mean-only baseline.
- A negative R² indicates performance worse than that baseline.
Step 7: Visualize the Regression Line
plt.figure(figsize=(8, 5))
plt.scatter(
X_test["bmi"], y_test,
alpha=0.7, label="Actual values"
)
order = np.argsort(X_test["bmi"].to_numpy())
plt.plot(
X_test["bmi"].to_numpy()[order],
y_pred[order],
label="Regression line"
)
plt.xlabel("Scaled BMI")
plt.ylabel("Disease progression")
plt.title("Simple Linear Regression")
plt.legend()
-
plt.show()
The scatter plot shows the actual test values, while the regression line shows the predicted values.
The vertical distance between a point and the line represents the prediction error for that sample.
5. Advantages and Limitations
Advantages
- Easy to understand and implement.
- Fast to train.
- Coefficients are interpretable.
- Useful as a baseline for more complex models.
Limitations
- Assumes a linear relationship between the features and target.
- Can be sensitive to outliers.
- May perform poorly when the relationship is nonlinear.
- A relationship between variables does not establish causation.
6. Conclusion
Linear regression is a useful starting point for numerical prediction problems. It provides a simple and interpretable way to model relationships between variables.
In this example, we used Python and scikit-learn to train a linear regression model, generate predictions, evaluate its performance, and visualize the regression line.
The same workflow can be extended to multiple linear regression by including additional input features.
Top comments (0)