Linear Regression
Overview and Core Concepts
Simple Linear Regression is one of the most foundational supervised machine learning algorithms. It serves as the primary building block for understanding predictive modeling, regression analysis, and machine learning workflows.
Linear Regression is a simple supervised machine learning algorithm that finds the best-fit straight line through the given data points to identify and model the relationship between independent variables (input features) and a dependent variable (target/output). It uses this relationship to predict continuous numerical values for new, unseen data.
Linear Regression Variants
- Simple Linear Regression: Modeling the relationship between a single numerical input feature (x) and a single continuous numerical output target (y).
- Multiple Linear Regression: Modeling the relationship between multiple numerical input features (x_1, x_2, ……., x_n) and a single target variable (y).
- Polynomial Linear Regression: Applying non-linear transformations to input features to fit non-linear data patterns.
- Regularized Linear Regression: Applying penalty terms (such as Ridge or Lasso regularization) to prevent overfitting.
2. Problem Statement and Baseline Intuition
Real-World Example Scenario
Consider a dataset collected from college campus placements containing records of placed students. The dataset consists of two primary numerical columns:
| Input Feature (X) | Output Target (Y) |
|---|---|
| Student CGPA | Salary Package (LPA) |
| 6.89 | 3.26 LPA |
| 8.05 | 4.10 LPA |
| 5.12 | 1.90 LPA |
The goal is to build a regression model that accepts a student’s CGPA (x) and accurately predicts their expected placement package (y).
Baseline Naive Prediction
If no input feature (x) were available, the simplest baseline prediction for any student’s package would be the arithmetic mean of all historical placement packages (e.g., predicting 3.5 LPA for everyone).
However, a naive mean prediction fails to differentiate between high-performing and low-performing students. Utilizing the CGPA feature allows the model to tailor predictions based on individual academic performance.

Mathematical Formulation and Parameter Interpretation
The mathematical equation representing a straight line in two-dimensional space is defined as:
y = mx + b
Equation Components
- y: The predicted output variable (Salary Package in LPA).
- x: The input feature variable (Student CGPA).
- m: The slope of the line (also referred to as weight, coefficient, or feature weightage).
- b: The y-intercept of the line (also referred to as offset or baseline bias).
Intuitive Interpretation of Parameters
1. Slope (m) – Feature Weightage
The slope measures the rate of change in the output variable per unit change in the input feature:
- A high positive value for m indicates high sensitivity; a small increase in CGPA results in a significant increase in predicted salary.
- A low value for m indicates low feature weightage; changes in CGPA have minimal impact on salary predictions.
2. Y-Intercept (b) – Offset / Baseline Value
The y-intercept represents the predicted target value when the input feature x = 0:
- Mathematically, if x = 0, then y = b.
- In real-world intuition, b acts as an offset or baseline starting value for predictions when feature values are zero or minimal.
How Does Linear Regression Calculate the Best-Fit Line?
Let’s understand the mathematics step by step using a simple example.
Equation of a Straight Line
Linear Regression uses the equation of a straight line to represent the relationship between input and output.
Understanding Slope (m)
Slope tells us how much the predicted output changes when the input increases by one unit.
Point A = (2, 3)
Point B = (4, 7)
m = 4 / 2
m = 2
The output increases by 2 units for every 1-unit increase in input.
Understanding Intercept (b)
The intercept is the predicted output when the input value is zero.
b = 3 − 4
b = −1
Constructing the Regression Line
Now substitute the calculated slope and intercept into the straight-line equation.
We have obtained a straight line passing through both example points.
| Input (x) | Calculation | Output (y) |
|---|---|---|
| 2 | 2 × 2 − 1 | 3 |
| 4 | 2 × 4 − 1 | 7 |
| 5 | 2 × 5 − 1 | 9 |
How Does Linear Regression Find the Best-Fit Line?
In real datasets, we generally have many data points that do not lie perfectly on a straight line. Linear Regression uses Ordinary Least Squares (OLS) to find the line that minimizes the sum of squared residuals.
Understanding Residuals
A residual is the difference between the actual output and the predicted output.
Suppose the actual output is 7 and the predicted output is 6.5.
Residual = 0.5
Mean Squared Error (MSE)
OLS minimizes the sum of squared residuals. MSE is the average of these squared errors.
Predicted = [2.5, 6.5]
Errors = [0.5, 0.5]
Squared errors = [0.25, 0.25]
MSE = (0.25 + 0.25) / 2
MSE = 0.25
Key Takeaway
Linear Regression calculates the slope and intercept, constructs a straight line, predicts output values, and uses the least-squares principle to find the best-fitting line.
| Google Colab Code | Click Here |
| Dataset | Click Here |
Evaluation Metrics for Regression
Evaluation Metrics for Regression
Once a regression model is trained, how do we evaluate its performance? Regression evaluation metrics measure the difference between actual and predicted values. They help us understand how accurately our model performs on unseen data.
Five major evaluation metrics are commonly used in regression:
1. Mean Absolute Error (MAE)
Mean Absolute Error (MAE) calculates the average absolute difference between actual and predicted values. It tells us how far the model’s predictions are from the actual values on average.
Where:
- n: Total number of observations.
- yi: Actual value.
- ŷi: Predicted value.
Understanding MAE with an Example
Suppose the actual package is 8 LPA and the model predicts 6 LPA. The absolute prediction error is:
MAE calculates the average of these absolute errors across all observations.
- Unit: Same unit as the target variable y, such as LPA.
- Advantage: Easy to understand and less sensitive to large errors than MSE.
- Disadvantage: The absolute value function is not differentiable at zero, which can make it less convenient for some optimization methods.
2. Mean Squared Error (MSE)
Mean Squared Error (MSE) calculates the average squared difference between actual and predicted values. Since errors are squared, larger prediction errors receive greater weight.
Where:
- n: Total number of observations.
- yi: Actual value.
- ŷi: Predicted value.
Understanding MSE with an Example
Suppose the prediction errors are 2 and 5. Their squared errors are:
The larger error contributes much more to MSE because the error is squared.
- Unit: Squared unit of the target variable, such as LPA².
- Advantage: Differentiable everywhere and useful as an optimization loss function.
- Disadvantage: Highly sensitive to outliers because large errors are squared. Its squared units can also be difficult to interpret.
3. Root Mean Squared Error (RMSE)
Root Mean Squared Error (RMSE) is the square root of Mean Squared Error. It measures the typical magnitude of prediction errors while expressing the result in the same unit as the target variable.
Understanding RMSE with an Example
If the MSE of a regression model is 4 LPA², then:
Taking the square root converts the error measurement back to the original unit.
- Unit: Same unit as the target variable.
- Advantage: Easier to interpret than MSE because it uses the original target unit.
- Disadvantage: Still sensitive to large errors and outliers.
Visual Understanding of Prediction Errors (Residuals)
A residual is the vertical difference between an actual data point and the value predicted by the regression line. It represents the prediction error for an individual observation.
In the diagram:
- Black dots: Actual observed data points.
- Red line: Regression model or best-fit line.
- Predicted value: Value estimated by the regression model.
- Residual: Vertical difference between the actual and predicted values.
MAE, MSE and RMSE use these residuals to measure the prediction errors of a regression model.
4. Coefficient of Determination (R² Score)
R² Score measures how well a regression model explains the variation in the target variable compared with a baseline model that always predicts the mean value of y.
Where:
- SSres: Residual Sum of Squares, representing the squared prediction errors of the regression model.
- SStot: Total Sum of Squares, representing the squared errors when predicting the mean of the actual values.
- ȳ: Mean of the actual target values.
Visual Understanding of R² Score
The following diagram compares the regression line with the mean line. It shows how total variation (SStot) and unexplained variation (SSres) are measured.
A smaller SSres compared with SStot generally indicates that the regression model explains more of the variation in the target variable.
Interpreting R² Values
- R² = 1: Perfect predictions on the evaluated dataset.
- R² = 0: The model performs like a baseline that always predicts the mean value.
- R² < 0: The model performs worse than the mean baseline.
Variance Interpretation: An R² score of 0.80 means that the model explains 80% of the variation in the target variable on the evaluated dataset. It does not mean that 80% of individual predictions are correct.
Important: R² is not restricted to values between 0 and 1. It can be negative, especially when evaluated on test data.
5. Adjusted R² Score
A limitation of standard R² is that adding more input features to a model trained on the same dataset cannot decrease its R² value. Even an irrelevant feature can increase or leave R² unchanged.
Adjusted R² addresses this issue by applying a penalty based on the number of independent input features.
Where:
- n: Total number of observations.
- k: Number of independent input features.
- R²: Standard coefficient of determination.
How Adjusted R² Behaves
- Adding a relevant feature: Adjusted R² may increase if the improvement in model fit justifies the additional feature.
- Adding an irrelevant feature: Adjusted R² may decrease because of the penalty for model complexity.
Adjusted R² is particularly useful when comparing multiple linear regression models with different numbers of predictors.
Note: For a model with an intercept, n must be greater than k + 1 for this formula to be defined.
6. Summary Comparison of Regression Metrics
The following table summarizes the five evaluation metrics, their units, sensitivity to outliers and common use cases.
| Metric | Formula | Unit | Outlier Sensitivity | Primary Use Case |
|---|---|---|---|---|
| MAE | Mean of |y – ŷ| | Same as y | Lower than MSE | Intuitive error reporting |
| MSE | Mean of (y – ŷ)² | Squared y | High | Optimization loss |
| RMSE | √MSE | Same as y | High | Error measurement |
| R² Score | 1 – SSres/SStot | Unitless | Can be affected by outliers | Goodness of fit |
| Adjusted R² | Adjusted R² formula | Unitless | Can be affected by outliers | Comparing regression models |
Key Takeaways
- Lower MAE means smaller average absolute prediction errors.
- Lower MSE means smaller average squared prediction errors.
- Lower RMSE means smaller typical prediction errors in the original target unit.
- Higher R² generally indicates that the model explains more variation in the target variable.
- Adjusted R² considers the number of input features when comparing regression models.
Always evaluate regression models using test data and select metrics according to the problem you are solving.
References
- Scikit-learn – Regression Metrics
- Scikit-learn – Mean Absolute Error
- Scikit-learn – Mean Squared Error
- Scikit-learn – R² Score
Diagram credits: The two regression diagrams are included from the image URLs supplied for this tutorial. Verify the original creators’ licences before republishing.
Simple Linear Regression Using Python
Learn how to build, train, predict and evaluate a Linear Regression model using Python and Scikit-learn.
Import Required Libraries
First, import the Python libraries required for data handling, numerical calculations, visualization and machine learning.
import pandas as pd
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
)
- Pandas: Loads and manages tabular datasets.
- NumPy: Performs mathematical and numerical operations.
- Matplotlib: Creates graphs and visualizations.
- Scikit-learn: Provides tools for training and evaluating machine learning models.
Load the Dataset
Load the placement dataset from a CSV file using Pandas. The dataset contains student CGPA and their corresponding placement packages.
df = pd.read_csv("placement.csv")
# Display the first five rows
print(df.head())
- read_csv(): Reads the CSV file and converts it into a DataFrame.
- df: Stores the loaded dataset.
- head(): Displays the first five rows by default.
Explore and Understand the Dataset
Before training a model, we should inspect the dataset to understand its size, columns, statistical information and missing values.
# Check number of rows and columns
df.shape
# Get statistical information
df.describe()
# Check missing values
df.isnull().sum()
# Check column names and data types
df.info()
- shape: Returns the number of rows and columns.
- describe(): Displays statistical values such as mean, standard deviation, minimum and maximum.
- isnull().sum(): Counts missing values in each column.
- info(): Displays column names, data types and non-null counts.
Select Input and Target Variables
Now identify which variable will be used as input and which variable the model needs to predict.
# Independent variable (input feature)
X = df[["cgpa"]]
# Dependent variable (target)
y = df["package"]
CGPA
Package
X: Contains the CGPA values that the model uses to make predictions.
y: Contains the actual package values that the model learns to predict.
We use double square brackets in df[["cgpa"]] to keep X as a two-dimensional DataFrame, as expected by Scikit-learn.
Split the Dataset into Training and Testing Data
We divide the dataset into two parts. The training data is used to teach the model, while the testing data is used to evaluate its predictions on unseen examples.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42
)
- X_train: Input features used for training.
- X_test: Input features reserved for testing.
- y_train: Actual target values used for training.
- y_test: Actual target values used to evaluate predictions.
- test_size=0.2: Reserves 20% of the data for testing.
- random_state=42: Makes the random split reproducible.
Create and Train the Model
After splitting the dataset, create a Linear Regression model and train it using the training data.
from sklearn.linear_model import LinearRegression
# Create the model
model = LinearRegression()
# Train the model
model.fit(X_train, y_train)
- LinearRegression(): Creates a Linear Regression model object.
- fit(): Trains the model using input features and their corresponding target values.
During training, the model estimates the slope and intercept that minimize the sum of squared residuals.
Extract Slope and Intercept
After training, we can access the learned coefficients of the Linear Regression model.
# Extract the slope
m = model.coef_[0]
# Extract the intercept
b = model.intercept_
print("Slope:", m)
print("Intercept:", b)
- coef_: Stores the learned coefficient or slope for each input feature.
- intercept_: Stores the estimated intercept.
These values are used to construct the regression equation.
Make Predictions
Use the trained model to predict package values for the testing dataset.
# Predict target values
y_pred = model.predict(X_test)
# Display predicted values
print(y_pred)
predict(): Takes input features and returns the output values estimated by the trained model.
The model uses the learned slope and intercept to calculate each prediction.
Evaluate Model Performance
After making predictions, compare the predicted values with the actual testing values to understand how well the model performs.
from sklearn.metrics import (
mean_absolute_error,
mean_squared_error,
r2_score
)
# Calculate evaluation metrics
mae = mean_absolute_error(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(y_test, y_pred)
print("MAE:", mae)
print("MSE:", mse)
print("RMSE:", rmse)
print("R2 Score:", r2)
- MAE: Measures the average absolute difference between actual and predicted values.
- MSE: Measures the average squared prediction error.
- RMSE: Square root of MSE, expressed in the target variable’s unit.
- R² Score: Measures how much variation in the target is explained by the model relative to predicting its mean.
Visualize the Regression Line
Finally, visualize the actual data points and the fitted regression line to understand the relationship between CGPA and package.
# Plot actual data points
plt.scatter(
X["cgpa"],
y,
color="blue",
label="Actual Data"
)
# Generate sorted CGPA values
X_line = pd.DataFrame({
"cgpa": np.linspace(
X["cgpa"].min(),
X["cgpa"].max(),
200
)
})
# Predict values for the regression line
y_line = model.predict(X_line)
# Plot the best-fit line
plt.plot(
X_line["cgpa"],
y_line,
color="red",
label="Best-Fit Line"
)
plt.xlabel("CGPA")
plt.ylabel("Package (LPA)")
plt.title("CGPA vs Package")
plt.legend()
plt.grid(alpha=0.3)
plt.show()
- scatter(): Displays the actual observations as points.
- linspace(): Generates evenly spaced CGPA values.
- predict(): Calculates predicted package values for the generated CGPA values.
- plot(): Draws the regression line.
We generate sorted CGPA values to draw a smooth, continuous regression line rather than connecting randomly ordered test points.
Visualize Actual vs Predicted Values
We can also compare actual and predicted values using a scatter plot. The vertical gaps represent prediction errors, also known as residuals.
plt.scatter(
X_test["cgpa"],
y_test,
color="blue",
label="Actual Values"
)
plt.scatter(
X_test["cgpa"],
y_pred,
color="orange",
marker="x",
label="Predicted Values"
)
# Draw residual lines
for x_value, actual, predicted in zip(
X_test["cgpa"], y_test, y_pred
):
plt.plot(
[x_value, x_value],
[actual, predicted],
color="green",
linestyle="--",
alpha=0.5
)
plt.xlabel("CGPA")
plt.ylabel("Package (LPA)")
plt.title("Actual vs Predicted Values")
plt.legend()
plt.grid(alpha=0.3)
plt.show()
- Blue dots: Actual package values.
- Orange crosses: Predicted package values.
- Green dashed lines: Differences between actual and predicted values.
Smaller vertical gaps indicate predictions closer to the actual observations.