The Wayback Machine - https://web.archive.org/web/20231220221601/https://www.geeksforgeeks.org/ml-linear-regression/
Open In App
Related Articles

Linear Regression in Machine learning

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Machine Learning is a branch of Artificial intelligence that focuses on the development of algorithms and statistical models that can learn from and make predictions on data. Linear regression is also a type of machine-learning algorithm more specifically a supervised machine-learning algorithm that learns from the labelled datasets and maps the data points to the most optimized linear functions. which can be used for prediction on new datasets. 

First of we should know what is supervised machine learning algorithms. It is a type of machine learning where the algorithm learns from labelled data.  Labeled data means the dataset whose respective target value is already known. Supervised learning has two types:

  • Classification: It predicts the class of the dataset based on the independent input variable. Class is the categorical or discrete values. like the image of an animal is a cat or dog?
  • Regression: It predicts the continuous output variables based on the independent input variable. like the prediction of house prices based on different parameters like house age, distance from the main road, location, area, etc.

Here, we will discuss one of the simplest types of regression i.e. Linear Regression.

Linear Regression in Machine learning

Linear regression is a type of supervised machine learning algorithm that computes the linear relationship between a dependent variable and one or more independent features. When the number of the independent feature, is 1 then it is known as Univariate Linear regression, and in the case of more than one feature, it is known as multivariate linear regression.

Assumption for Linear Regression Model

Linear regression is a powerful tool for understanding and predicting the behaviour of a variable, however, it needs to meet a few conditions in order to be accurate and dependable solutions. 

  1. Linearity: The independent and dependent variables have a linear relationship with one another. This implies that changes in the dependent variable follow those in the independent variable(s) in a linear fashion. This means that there should be a straight line that can be drawn through the data points. If the relationship is not linear, then linear regression will not be an accurate model.
  2. Independence: The observations in the dataset are independent of each other. This means that the value of the dependent variable for one observation does not depend on the value of the dependent variable for another observation. If the observations are not independent, then linear regression will not be an accurate model.
  3. Homoscedasticity: Across all levels of the independent variable(s), the variance of the errors is constant. This indicates that the amount of the independent variable(s) has no impact on the variance of the errors. If the variance of the residuals is not constant, then linear regression will not be an accurate model.

    Homoscedasticity in Linear Regression

  4. Normality: The residuals should be normally distributed. This means that the residuals should follow a bell-shaped curve. If the residuals are not normally distributed, then linear regression will not be an accurate model.
  5. No multicollinearity: There is no high correlation between the independent variables. This indicates that there is little or no correlation between the independent variables.Multicollinearity occurs when two or more independent variables are highly correlated with each other, which can make it difficult to determine the individual effect of each variable on the dependent variable. If there is multicollinearity, then linear regression will not be an accurate model.

Types of Linear Regression

There are two main types of linear regression:

  • Simple Linear Regression: This is the simplest form of linear regression, and it involves only one independent variable and one dependent variable. The equation for simple linear regression is:
    y=\beta_{0}+\beta_{1}X
    where:
    • Y is the dependent variable
    • X is the independent variable
    • β0 is the intercept
    • β1 is the slope
  • Multiple Linear Regression: This involves more than one independent variable and one dependent variable. The equation for multiple linear regression is:
    y=\beta_{0}+\beta_{1}X+\beta_{2}X+.........\beta_{n}X
    where:
    • Y is the dependent variable
    • X1, X2, …, Xp are the independent variables
    • β0 is the intercept
    • β1, β2, …, βn are the slopes

Some other regression types are-

  • Polynomial Regression – Polynomial regression goes beyond simple linear regression by incorporating higher-order polynomial terms of the independent variable(s) into the model. It is represented by the general equation:
  • Ridge Regression – Ridge regression is a regularization technique used to prevent overfitting in linear regression models, especially when dealing with multiple independent variables. It introduces a penalty term to the least squares objective function, biasing the model towards solutions with smaller coefficients. The equation for ridge regression becomes:
  • Lasso Regression – Lasso regression is another regularization technique that uses an L1 penalty term to shrink the coefficients of less important independent variables towards zero, effectively performing feature selection. The equation for lasso regression becomes:
  • Elastic Net Regression – Elastic net regression combines the penalties of ridge and lasso regression, offering a balance between their strengths. It uses a mixed penalty term of the form

The goal of the algorithm is to find the best Fit Line equation that can predict the values based on the independent variables.

In regression set of records are present with X and Y values and these values are used to learn a function so if you want to predict Y from an unknown X this learned function can be used. In regression we have to find the value of Y, So, a function is required that predicts continuous Y in the case of regression given X as independent features.

What is the best Fit Line?

Our primary objective while using linear regression is to locate the best-fit line, which implies that the error between the predicted and actual values should be kept to a minimum. There will be the least error in the best-fit line.

The best Fit Line equation provides a straight line that represents the relationship between the dependent and independent variables. The slope of the line indicates how much the dependent variable changes for a unit change in the independent variable(s).

11111111

Linear Regression

Here Y is called a dependent or target variable and X is called an independent variable also known as the predictor of Y. There are many types of functions or modules that can be used for regression. A linear function is the simplest type of function. Here, X may be a single feature or multiple features representing the problem.

Linear regression performs the task to predict a dependent variable value (y) based on a given independent variable (x)). Hence, the name is Linear Regression. In the figure above, X (input) is the work experience and Y (output) is the salary of a person. The regression line is the best-fit line for our model. 

We utilize the cost function to compute the best values in order to get the best fit line since different values for weights or the coefficient of lines result in different regression lines.

Hypothesis function for Linear Regression

As we have assumed earlier that our independent feature is the experience i.e X and the respective salary Y is the dependent variable. Let’s assume there is a linear relationship between X and Y then the salary can be predicted using:

\hat{Y} = \theta_1 + \theta_2X

OR

\hat{y}_i = \theta_1 + \theta_2x_i

Here,

  • y_i \epsilon Y \;\; (i= 1,2, \cdots , n)                      are labels to data (Supervised learning)
  • x_i \epsilon X \;\; (i= 1,2, \cdots , n)                      are the input independent training data (univariate – one input variable(parameter)) 
  • \hat{y_i} \epsilon \hat{Y} \;\; (i= 1,2, \cdots , n)                      are the predicted values.

The model gets the best regression fit line by finding the best θ1 and θ2 values. 

  • θ1: intercept 
  • θ2: coefficient of x 

Once we find the best θ1 and θ2 values, we get the best-fit line. So when we are finally using our model for prediction, it will predict the value of y for the input value of x. 

Cost function for Linear Regression

The cost function or the loss function is nothing but the error or difference between the predicted value \hat{Y}                      and the true value Y. It is the Mean Squared Error (MSE) between the predicted value and the true value. The cost function (J) can be written as:

\text{Cost function}(J) = \frac{1}{n}\sum_{n}^{i}(\hat{y_i}-y_i)^2

How to update θ1 and θ2 values to get the best-fit line? 

To achieve the best-fit regression line, the model aims to predict the target value \hat{Y}                      such that the error difference between the predicted value \hat{Y}                      and the true value Y is minimum. So, it is very important to update the θ1 and θ2 values, to reach the best value that minimizes the error between the predicted y value (pred) and the true y value (y). 

minimize\frac{1}{n}\sum_{i=1}^{n}(\hat{y_i}-y_i)^2

Gradient Descent for Linear Regression

A linear regression model can be trained using the optimization algorithm gradient descent by iteratively modifying the model’s parameters to reduce the mean squared error (MSE) of the model on a training dataset. To update θ1 and θ2 values in order to reduce the Cost function (minimizing RMSE value) and achieve the best-fit line the model uses Gradient Descent. The idea is to start with random θ1 and θ2 values and then iteratively update the values, reaching minimum cost. 

A gradient is nothing but a derivative that defines the effects on outputs of the function with a little bit of variation in inputs.

Let’s differentiate the cost function(J) with respect to \theta_1                       

\begin {aligned} {J}'_{\theta_1} &=\frac{\partial J(\theta_1,\theta_2)}{\partial \theta_1} \\ &= \frac{\partial}{\partial \theta_1} \left[\frac{1}{n} \left(\sum_{i=1}^{n}(\hat{y}_i-y_i)^2 \right )\right] \\ &= \frac{1}{n}\left[\sum_{i=1}^{n}2(\hat{y}_i-y_i) \left(\frac{\partial}{\partial \theta_1}(\hat{y}_i-y_i) \right ) \right] \\ &= \frac{1}{n}\left[\sum_{i=1}^{n}2(\hat{y}_i-y_i) \left(\frac{\partial}{\partial \theta_1}( \theta_1 + \theta_2x_i-y_i) \right ) \right] \\ &= \frac{1}{n}\left[\sum_{i=1}^{n}2(\hat{y}_i-y_i) \left(1+0-0 \right ) \right] \\ &= \frac{1}{n}\left[\sum_{i=1}^{n}(\hat{y}_i-y_i) \left(2 \right ) \right] \\ &= \frac{2}{n}\sum_{i=1}^{n}(\hat{y}_i-y_i) \end {aligned}

Let’s differentiate the cost function(J) with respect to \theta_2

\begin {aligned} {J}'_{\theta_2} &=\frac{\partial J(\theta_1,\theta_2)}{\partial \theta_2} \\ &= \frac{\partial}{\partial \theta_2} \left[\frac{1}{n} \left(\sum_{i=1}^{n}(\hat{y}_i-y_i)^2 \right )\right] \\ &= \frac{1}{n}\left[\sum_{i=1}^{n}2(\hat{y}_i-y_i) \left(\frac{\partial}{\partial \theta_2}(\hat{y}_i-y_i) \right ) \right] \\ &= \frac{1}{n}\left[\sum_{i=1}^{n}2(\hat{y}_i-y_i) \left(\frac{\partial}{\partial \theta_2}( \theta_1 + \theta_2x_i-y_i) \right ) \right] \\ &= \frac{1}{n}\left[\sum_{i=1}^{n}2(\hat{y}_i-y_i) \left(0+x_i-0 \right ) \right] \\ &= \frac{1}{n}\left[\sum_{i=1}^{n}(\hat{y}_i-y_i) \left(2x_i \right ) \right] \\ &= \frac{2}{n}\sum_{i=1}^{n}(\hat{y}_i-y_i)\cdot x_i \end {aligned}

Finding the coefficients of a linear equation that best fits the training data is the objective of linear regression. By moving in the direction of the Mean Squared Error negative gradient with respect to the coefficients, the coefficients can be changed. And the respective intercept and coefficient of X will be if \alpha                      is the learning rate.

Gradient Descent -Geeksforgeeks

Gradient Descent

\begin{aligned} \theta_1 &= \theta_1 - \alpha \left( {J}'_{\theta_1}\right) \\&=\theta_1 -\alpha \left( \frac{2}{n}\sum_{i=1}^{n}(\hat{y}_i-y_i)\right) \end{aligned} \\ \begin{aligned} \theta_2 &= \theta_2 - \alpha \left({J}'_{\theta_2}\right) \\&=\theta_2 - \alpha \left(\frac{2}{n}\sum_{i=1}^{n}(\hat{y}_i-y_i)\cdot x_i\right) \end{aligned}

Evaluation Metrics for Linear Regression

A variety of evaluation measures can be used to determine the strength of any linear regression model. These assessment metrics often give an indication of how well the model is producing the observed outputs.

The most common measurements are:

  • Coefficient of Determination (R-squared): R-Squared is a statistic that indicates how much variation the developed model can explain or capture. It is always in the range of 0 to 1. In general, the better the model matches the data, the greater the R-squared number.
    In mathematical notation, it can be expressed as :
    R^{2}=1-(^{\frac{RSS}{TSS}})
    • Residual sum of Squares (RSS)– The sum of squares of the residual for each data point in the plot or data is known as the residual sum of squares, or RSS. It is a measurement of the difference between the output that was observed and what was anticipated.
      RSS=\sum_{i=2}^{n}(y_{i}-b_{0}-b_{1}x_{i})^{2}
    • Total Sum of Squares (TSS)– The sum of the data points’ errors from the answer variable’s mean is known as the total sum of squares, or TSS.
      TSS= \sum_{}^{}(y-\overline{y_{i}})^2
  • Root Mean Squared Error (RMSE): The square root of the residuals’ variance is the Root Mean Squared Error. It describes how well the observed data points match the expected values, or the model’s absolute fit to the data.
    In mathematical notation, it can be expressed as:
    RMSE=\sqrt{\frac{RSS}{n}}=\sqrt\frac{{{\sum_{i=2}^{n}(y^{actual}_{i}}- y_{i}^{predicted})^2}}{n}
    Rather than dividing the entire number of data points in the model by the number of degrees of freedom, one must divide the sum of the squared residuals to obtain an unbiased estimate. Then, this figure is referred to as the Residual Standard Error (RSE). In mathematical notation, it can be expressed as:
    RMSE=\sqrt{\frac{RSS}{n}}=\sqrt\frac{{{\sum_{i=2}^{n}(y^{actual}_{i}}- y_{i}^{predicted})^2}}{(n-2)}
    RSME is not as good of a metric as R-squared. Root Mean Squared Error can fluctuate when the units of the variables vary since its value is dependent on the variables’ units (it is not a normalized measure).

Build the Linear Regression model from Scratch

Import the necessary libraries:

Python3




import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.axes as ax
from matplotlib.animation import FuncAnimation


Load the dataset and separate input and Target variables

Here is the link for dataset: Dataset Link

Python3




data = pd.read_csv(url)
data
 
# Drop the missing values
data = data.dropna()
 
# training dataset and labels
train_input = np.array(data.x[0:500]).reshape(500, 1)
train_output = np.array(data.y[0:500]).reshape(500, 1)
 
# valid dataset and labels
test_input = np.array(data.x[500:700]).reshape(199, 1)
test_output = np.array(data.y[500:700]).reshape(199, 1)


Build the Linear Regression Model and Plot the regression line

Steps:

  • In forward propagation, Linear regression function Y=mx+x is applied by initially assigning random value of parameter (m & c).
  • The we have written the function to finding the cost function i.e the mean 

Python3




class LinearRegression:
    def __init__(self):
        self.parameters = {}
 
    def forward_propagation(self, train_input):
        m = self.parameters['m']
        c = self.parameters['c']
        predictions = np.multiply(m, train_input) + c
        return predictions
 
    def cost_function(self, predictions, train_output):
        cost = np.mean((train_output - predictions) ** 2)
        return cost
 
    def backward_propagation(self, train_input, train_output, predictions):
        derivatives = {}
        df = (train_output - predictions) * -1
        dm = np.mean(np.multiply(train_input, df))
        dc = np.mean(df)
        derivatives['dm'] = dm
        derivatives['dc'] = dc
        return derivatives
 
    def update_parameters(self, derivatives, learning_rate):
        self.parameters['m'] = self.parameters['m'] - \
            learning_rate * derivatives['dm']
        self.parameters['c'] = self.parameters['c'] - \
            learning_rate * derivatives['dc']
 
    def train(self, train_input, train_output, learning_rate, iters):
        # Initialize random parameters
        self.parameters['m'] = np.random.uniform(0, 1) * -1
        self.parameters['c'] = np.random.uniform(0, 1) * -1
 
        # Initialize loss
        self.loss = []
 
        # Initialize figure and axis for animation
        fig, ax = plt.subplots()
        x_vals = np.linspace(min(train_input), max(train_input), 100)
        line, = ax.plot(x_vals, self.parameters['m'] * x_vals +
                        self.parameters['c'], color='red', label='Regression Line')
        ax.scatter(train_input, train_output, marker='o',
                   color='green', label='Training Data')
 
        # Set y-axis limits to exclude negative values
        ax.set_ylim(0, max(train_output) + 1)
 
        def update(frame):
            # Forward propagation
            predictions = self.forward_propagation(train_input)
 
            # Cost function
            cost = self.cost_function(predictions, train_output)
 
            # Back propagation
            derivatives = self.backward_propagation(
                train_input, train_output, predictions)
 
            # Update parameters
            self.update_parameters(derivatives, learning_rate)
 
            # Update the regression line
            line.set_ydata(self.parameters['m']
                           * x_vals + self.parameters['c'])
 
            # Append loss and print
            self.loss.append(cost)
            print("Iteration = {}, Loss = {}".format(frame + 1, cost))
 
            return line,
          # Create animation
        ani = FuncAnimation(fig, update, frames=iters, interval=200, blit=True)
 
        # Save the animation as a video file (e.g., MP4)
        ani.save('linear_regression_A.mp4', writer='ffmpeg')
 
        plt.xlabel('Input')
        plt.ylabel('Output')
        plt.title('Linear Regression')
        plt.legend()
        plt.show()
 
        return self.parameters, self.loss


Trained the model and Final Prediction

Python3




#Example usage
linear_reg = LinearRegression()
parameters, loss = linear_reg.train(train_input, train_output, 0.0001, 20)


Output:

Iteration = 1, Loss = 5363.981028641572
Iteration = 2, Loss = 2437.9165904342512
Iteration = 3, Loss = 1110.3579137897523
Iteration = 4, Loss = 508.043071737168
Iteration = 5, Loss = 234.7721607488976
Iteration = 6, Loss = 110.78884574712548
Iteration = 7, Loss = 54.53747840152165
Iteration = 8, Loss = 29.016170730218153
Iteration = 9, Loss = 17.43712517102535
Iteration = 10, Loss = 12.183699375121314
Iteration = 11, Loss = 9.800214272338595
Iteration = 12, Loss = 8.718824440889573
Iteration = 13, Loss = 8.228196676299069
Iteration = 14, Loss = 8.005598315794709
Iteration = 15, Loss = 7.904605192804647
Iteration = 16, Loss = 7.858784500769819
Iteration = 17, Loss = 7.837995601770647
Iteration = 18, Loss = 7.828563654998014
Iteration = 19, Loss = 7.824284370030002
Iteration = 20, Loss = 7.822342853430061

ezgif-1-ba0c9540c5

Linear Regression Line

The linear regression line provides valuable insights into the relationship between the two variables. It represents the best-fitting line that captures the overall trend of how a dependent variable (Y) changes in response to variations in an independent variable (X).

  • Positive Linear Regression Line: A positive linear regression line indicates a direct relationship between the independent variable (X) and the dependent variable (Y). This means that as the value of X increases, the value of Y also increases. The slope of a positive linear regression line is positive, meaning that the line slants upward from left to right.
  • Negative Linear Regression Line: A negative linear regression line indicates an inverse relationship between the independent variable (X) and the dependent variable (Y). This means that as the value of X increases, the value of Y decreases. The slope of a negative linear regression line is negative, meaning that the line slants downward from left to right.

Applications of Linear Regression

Linear regression is used in many different fields, including finance, economics, and psychology, to understand and predict the behavior of a particular variable. For example, in finance, linear regression might be used to understand the relationship between a company’s stock price and its earnings or to predict the future value of a currency based on its past performance.

Advanatges of Linear Regression

  • Linear regression is a relatively simple algorithm, making it easy to understand and implement. The coefficients of the linear regression model can be interpreted as the change in the dependent variable for a one-unit change in the independent variable, providing insights into the relationships between variables.
  • Linear regression is computationally efficient and can handle large datasets effectively. It can be trained quickly on large datasets, making it suitable for real-time applications.
  • Linear regression is relatively robust to outliers compared to other machine learning algorithms. Outliers may have a smaller impact on the overall model performance.
  • Linear regression often serves as a good baseline model for comparison with more complex machine learning algorithms.
  • Linear regression is a well-established algorithm with a rich history and is widely available in various machine learning libraries and software packages.

Disadvantages of Linear Regression

  • Linear regression assumes a linear relationship between the dependent and independent variables. If the relationship is not linear, the model may not perform well.
  • Linear regression is sensitive to multicollinearity, which occurs when there is a high correlation between independent variables. Multicollinearity can inflate the variance of the coefficients and lead to unstable model predictions.
  • Linear regression assumes that the features are already in a suitable form for the model. Feature engineering may be required to transform features into a format that can be effectively used by the model.
  • Linear regression is susceptible to both overfitting and underfitting. Overfitting occurs when the model learns the training data too well and fails to generalize to unseen data. Underfitting occurs when the model is too simple to capture the underlying relationships in the data.
  • Linear regression provides limited explanatory power for complex relationships between variables. More advanced machine learning techniques may be necessary for deeper insights.

Conclusion

Linear regression is a fundamental machine learning algorithm that has been widely used for many years due to its simplicity, interpretability, and efficiency. It is a valuable tool for understanding relationships between variables and making predictions in a variety of applications. However, it is important to be aware of its limitations, such as its assumption of linearity and sensitivity to multicollinearity. When these limitations are carefully considered, linear regression can be a powerful tool for data analysis and prediction.

Frequently Asked Questions (FAQs)

1. What is linear regression?

Linear regression is a supervised machine learning algorithm that predicts a continuous target variable based on one or more independent variables. It assumes a linear relationship between the dependent and independent variables and uses a linear equation to model this relationship.

2. When is linear regression used?

Linear regression is commonly used for:

  • Predicting numerical values based on input features
  • Forecasting future trends based on historical data
  • Identifying correlations between variables
  • Understanding the impact of different factors on a particular outcome

3. How does linear regression work?

Linear regression fits a linear equation to the training data using a method called least squares. The goal is to find the values of the coefficients in the linear equation that minimize the sum of the squared residuals. Once the coefficients are found, the linear equation can be used to make predictions for new data points.

4. How do you evaluate the performance of a linear regression model?

There are several metrics that can be used to evaluate the performance of a linear regression model, such as:

  • Mean squared error (MSE): Measures the average squared difference between the predicted and actual values.
  • Root mean squared error (RMSE): The square root of the MSE.
  • Mean absolute error (MAE): Measures the average absolute difference between the predicted and actual values.
  • R-squared: A measure of how well the model explains the variation in the dependent variable.

5. How do you deal with outliers in linear regression?

Outliers can have a significant impact on the performance of a linear regression model. Techniques such as outlier detection and robust regression can be used to mitigate their effects.

6. How do you avoid overfitting and underfitting in linear regression?

Overfitting occurs when a model learns the training data too well and fails to generalize to unseen data. Underfitting occurs when a model is too simple to capture the underlying relationships in the data. To avoid these problems, techniques such as regularization and cross-validation can be used.


Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.
Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Last Updated : 29 Nov, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials