DocsStation
ML

Linear Regression

By csestudy247 Updated December 2, 2026 16 min read
16 min read

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 CGPASalary Package (LPA)
6.893.26 LPA
8.054.10 LPA
5.121.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.

Linear Regression

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.

Animated explanation of how linear regression finds the best-fit line
MATHEMATICAL FORMULATION

How Does Linear Regression Calculate the Best-Fit Line?

Let’s understand the mathematics step by step using a simple example.

01

Equation of a Straight Line

Linear Regression uses the equation of a straight line to represent the relationship between input and output.

y = mx + b
yPredicted output
xInput feature
mSlope of the line
bY-intercept
02

Understanding Slope (m)

Slope tells us how much the predicted output changes when the input increases by one unit.

m = (y₂ − y₁) / (x₂ − x₁)
Example: Two data points

Point A = (2, 3)

Point B = (4, 7)

m = (7 − 3) / (4 − 2)
m = 4 / 2
m = 2

The output increases by 2 units for every 1-unit increase in input.

03

Understanding Intercept (b)

The intercept is the predicted output when the input value is zero.

b = y − mx
Using Point A = (2, 3)
b = 3 − (2 × 2)
b = 3 − 4
b = −1
04

Constructing the Regression Line

Now substitute the calculated slope and intercept into the straight-line equation.

y = mx + b
y = 2x − 1

We have obtained a straight line passing through both example points.

Input (x)CalculationOutput (y)
22 × 2 − 13
42 × 4 − 17
52 × 5 − 19
05

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.

m = Σ(xᵢ − x̄)(yᵢ − ȳ) / Σ(xᵢ − x̄)²
b = ȳ − m x̄
Note: These formulas calculate the slope and intercept using all training data points, rather than just two points.
06

Understanding Residuals

A residual is the difference between the actual output and the predicted output.

Residual = Actual − Predicted

Suppose the actual output is 7 and the predicted output is 6.5.

Residual = 7 − 6.5
Residual = 0.5
07

Mean Squared Error (MSE)

OLS minimizes the sum of squared residuals. MSE is the average of these squared errors.

MSE = (1/n) Σ(yᵢ − ŷᵢ)²
Example: Actual and predicted values
Actual = [3, 7]
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 CodeClick Here
DatasetClick 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.

MAE = (1/n) ∑i=1n |yi – ŷi|

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:

|8 – 6| = 2 LPA

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.

MSE = (1/n) ∑i=1n (yi – ŷi)2

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:

2² = 4     5² = 25

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.

RMSE = √MSE
RMSE = √[ (1/n) ∑i=1n (yi – ŷi)2 ]

Understanding RMSE with an Example

If the MSE of a regression model is 4 LPA², then:

RMSE = √4 = 2 LPA

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.

Linear regression residual diagram showing data points, model line, actual value, predicted value and residual
Figure 1: Actual values, predicted values and residuals in a linear regression model.

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.

R² = 1 – (SSres / SStot)
R² = 1 – [ ∑(yi – ŷi)² / ∑(yi – ȳ)² ]

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.

Visual intuition of R squared showing mean line, regression line, residual sum of squares and total sum of squares
Figure 2: Visual understanding of R², total sum of squares (SStot) and residual sum of squares (SSres).

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.

Adjusted R² = 1 – [ (1 – R²)(n – 1) / (n – 1 – k) ]

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

Diagram credits: The two regression diagrams are included from the image URLs supplied for this tutorial. Verify the original creators’ licences before republishing.

PRACTICAL IMPLEMENTATION

Simple Linear Regression Using Python

Learn how to build, train, predict and evaluate a Linear Regression model using Python and Scikit-learn.

01

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
)
Understanding the libraries
  • 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.
02

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())
Explanation
  • 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.
03

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()
What do these methods do?
  • 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.
04

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"]
X Input Feature

CGPA

y Target Variable

Package

Explanation

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.

05

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
)
80% Training Data
20% Testing Data
Understanding the parameters
  • 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.
06

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)
Explanation
  • 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.

ŷ = mx + b The learned regression equation
07

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)
Explanation
  • 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.

08

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)
Explanation

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.

09

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)
Understanding evaluation metrics
  • 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.
Lower MAE, MSE and RMSE generally indicate smaller prediction errors. A higher R² indicates better performance relative to the mean-prediction baseline. R² can also be negative on test data.
10

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()
Explanation
  • 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.

11

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()
Explanation
  • 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.

Summary: Complete Linear Regression Workflow

Load Dataset ↓ Explore Data ↓ Select X and y ↓ Train-Test Split ↓ Train Model ↓ Make Predictions ↓ Evaluate Model ↓ Visualize Results

This is the basic workflow for implementing Simple Linear Regression using Python and Scikit-learn.

Scroll to Top