The Wayback Machine - https://web.archive.org/web/20240930173444/https://www.geeksforgeeks.org/gradient-descent-in-linear-regression/
Open In App

Gradient Descent in Linear Regression

Last Updated : 30 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

We know that in any machine learning project our main aim relies on how good our project accuracy is or how much our model prediction differs from the actual data point. Based on the difference between model prediction and actual data points we try to find the parameters of the model which give better accuracy on our dataset\, In order to find these parameters we apply gradient descent on the cost function of the machine learning model. 

What is Gradient Descent

Gradient Descent is an iterative optimization algorithm that tries to find the optimum value (Minimum/Maximum) of an objective function. It is one of the most used optimization techniques in machine learning projects for updating the parameters of a model in order to minimize a cost function.  

The main aim of gradient descent is to find the best parameters of a model which gives the highest accuracy on training as well as testing datasets. In gradient descent, The gradient is a vector that points in the direction of the steepest increase of the function at a specific point. Moving in the opposite direction of the gradient allows the algorithm to gradually descend towards lower values of the function, and eventually reaching to the minimum of the function.

Steps Required in Gradient Descent Algorithm 

  • Step 1 we first initialize the parameters of the model randomly 
  • Step 2 Compute the gradient of the cost function with respect to each parameter. It involves making partial differentiation of cost function with respect to the parameters. 
  • Step 3 Update the parameters of the model by taking steps in the opposite direction of the model. Here we choose a hyperparameter learning rate which is denoted by alpha. It helps in deciding the step size of the gradient. 
  • Step 4 Repeat steps 2 and 3 iteratively to get the best parameter for the defined model 

Pseudocode for Gradient Descent 

t ← 0
max_iterations ← 1000
w, b ← initialize randomly

while t < max_iterations do
t ← t + 1
w_t+1 ← w_t − η ∇w_t
b_t+1 ← b_t − η ∇b_t
end

Here    max_iterations is the number of iteration we want to do to update our parameter 

W,b are the weights and bias parameter 

η is the learning parameter also denoted by alpha  

To apply this gradient descent on data using any programming language we have to make four new functions using which we can update our parameter and apply it to data to make a prediction. We will see each function one by one and understand it 

  1.  gradient_descent – In the gradient descent function we will make the prediction on a dataset and compute the difference between the predicted and actual target value and accordingly we will update the parameter and hence it will return the updated parameter.
  2. compute_predictions – In this function, we will compute the prediction using the parameters at each iteration.
  3. compute_gradient – In this function we will compute the error which is the difference between the actual and predicted target value and then compute the gradient using this error and training data. 
  4. update_parameters – In this separate function we will update the parameter using learning rate and gradient that we got from the compute_gradient function. 

function gradient_descent(X, y, learning_rate, num_iterations):
Initialize parameters = θ
for iter in range(num_iterations):
predictions = compute_predictions(X, θ)
gradient = compute_gradient(X, y, predictions)
update_parameters(θ, gradient, learning_rate)
return θ

function compute_predictions(X, θ):
return X*θ

function compute_gradient(X, y, predictions):
error = predictions - y
gradient = Xᵀ * error / m
return gradient

function update_parameters(θ, gradient, learning_rate):
θ = θ - learning_rate ⨉ gradient

Mathematics Behind Gradient Descent 

In the Machine Learning Regression problem, our model targets to get the best-fit regression line to predict the value y based on the given input value (x). While training the model, the model calculates the cost function like Root Mean Squared error between the predicted value (pred) and true value (y). Our model targets to minimize this cost function. 
To minimize this cost function, the model needs to have the best value of θ1 and θ2(for Univariate linear regression problem). Initially model selects θ1 and θ2 values randomly and then iteratively update these value in order to minimize the cost function until it reaches the minimum. By the time model achieves the minimum cost function, it will have the best θ1 and θ2 values. Using these updated values of θ1 and θ2 in the hypothesis equation of linear equation, our model will predict the output value y.  

How do θ1 and θ2 values get updated?  

Linear Regression Cost Function: [Tex]J(\theta) = \frac{1}{2m} \sum_{i=1}^{m} (h_\theta(x^{(i)}) – y^{(i)})^2[/Tex]

so our model aim is to Minimize  \frac{1}{2m} \sum_{i=1}^{m} (h_\theta(x^{(i)}) – y^{(i)})^2  and store the parameters which makes it minimum. 

Gradient Descent Algorithm For Linear Regression 

Gradient descent algorithm for linear regression

Gradient descent algorithm for linear regression 

-> θj : Weights of the hypothesis.
-> hθ(xi) : predicted y value for ith input.
-> i : Feature index number (can be 0, 1, 2, ......, n).
-> α : Learning Rate of Gradient Descent.

How Does Gradient Descent Work  

Gradient descent works by moving downward toward the pits or valleys in the graph to find the minimum value. This is achieved by taking the derivative of the cost function, as illustrated in the figure below. During each iteration, gradient descent step-downs the cost function in the direction of the steepest descent. By adjusting the parameters in this direction, it seeks to reach the minimum of the cost function and find the best-fit values for the parameters. The size of each step is determined by parameter α known as Learning Rate. 
In the Gradient Descent algorithm, one can infer two points : 

  • If slope is +ve : θj = θj – (+ve value). Hence the value of θj decreases.
If slope is +ve in Gradient Descent

If slope is +ve in Gradient Descent 

  • If slope is -ve : θj = θj – (-ve value). Hence the value of θj increases.
If slope is -ve in Gradient Descent

If slope is -ve in Gradient Descent 

How To Choose Learning Rate 

The choice of correct learning rate is very important as it ensures that Gradient Descent converges in a reasonable time. : 

  • If we choose α to be very large, Gradient Descent can overshoot the minimum. It may fail to converge or even diverge. 
     
Effect of large alpha value on Gradient Descent

Effect of large alpha value on Gradient Descent 

  • If we choose α to be very small, Gradient Descent will take small steps to reach local minima and will take a longer time to reach minima. 
     

Effect of small alpha value on Gradient Descent 

Python Implementation of Gradient Descent 

At first, we will import all the necessary Python libraries that we will need for mathematical computation and plotting like numpy for mathematical operations and matplotlib for plotting. Then we will define a class Linear_Regression that represents the linear regression model.

We will make a update_coeffs method inside the class to update the coefficients (parameters) of the linear regression model using gradient descent. To calculate the error between the predicted output and the actual output we will make a predict method that will make predictions using the current model coefficients. 

For updating and calculating the gradient of the error we will make compute_cost which will apply gradient descent on (mean squared error) between the predicted values and the actual values.

Python

# Implementation of gradient descent in linear regression import numpy as np import matplotlib.pyplot as plt class Linear_Regression: def __init__(self, X, Y): self.X = X self.Y = Y self.b = [0, 0] def update_coeffs(self, learning_rate): Y_pred = self.predict() Y = self.Y m = len(Y) self.b[0] = self.b[0] - (learning_rate * ((1/m) * np.sum(Y_pred - Y))) self.b[1] = self.b[1] - (learning_rate * ((1/m) * np.sum((Y_pred - Y) * self.X))) def predict(self, X=[]): Y_pred = np.array([]) if not X: X = self.X b = self.b for x in X: Y_pred = np.append(Y_pred, b[0] + (b[1] * x)) return Y_pred def get_current_accuracy(self, Y_pred): p, e = Y_pred, self.Y n = len(Y_pred) return 1-sum( [ abs(p[i]-e[i])/e[i] for i in range(n) if e[i] != 0] )/n # def predict(self, b, yi): def compute_cost(self, Y_pred): m = len(self.Y) J = (1 / 2*m) * (np.sum(Y_pred - self.Y)**2) return J def plot_best_fit(self, Y_pred, fig): f = plt.figure(fig) plt.scatter(self.X, self.Y, color='b') plt.plot(self.X, Y_pred, color='g') f.show() def main(): X = np.array([i for i in range(11)]) Y = np.array([2*i for i in range(11)]) regressor = Linear_Regression(X, Y) iterations = 0 steps = 100 learning_rate = 0.01 costs = [] # original best-fit line Y_pred = regressor.predict() regressor.plot_best_fit(Y_pred, 'Initial Best Fit Line') while 1: Y_pred = regressor.predict() cost = regressor.compute_cost(Y_pred) costs.append(cost) regressor.update_coeffs(learning_rate) iterations += 1 if iterations % steps == 0: print(iterations, "epochs elapsed") print("Current accuracy is :", regressor.get_current_accuracy(Y_pred)) stop = input("Do you want to stop (y/*)??") if stop == "y": break # final best-fit line regressor.plot_best_fit(Y_pred, 'Final Best Fit Line') # plot to verify cost function decreases h = plt.figure('Verification') plt.plot(range(iterations), costs, color='b') h.show() # if user wants to predict using the regressor: regressor.predict([i for i in range(10)]) if __name__ == '__main__': main()

Output:

100 epochs elapsed
Current accuracy is : 0.9836456109008862

Regression line before gradient descent iteration

Regression line before gradient descent iteration 

Regression line after gradient descent iteration

Regression line after gradient descent iteration 

Accuracy graph for gradient descent on model 

Note: Gradient descent sometimes is also implemented using Regularization.

Advantages Of Gradient Descent 

  • Flexibility: Gradient Descent can be used with various cost functions and can handle non-linear regression problems.
  • Scalability: Gradient Descent is scalable to large datasets since it updates the parameters for each training example one at a time.
  • Convergence: Gradient Descent can converge to the global minimum of the cost function, provided that the learning rate is set appropriately.

Disadvantages Of Gradient Descent 

  • Sensitivity to Learning Rate: The choice of learning rate can be critical in Gradient Descent since using a high learning rate can cause the algorithm to overshoot the minimum, while a low learning rate can make the algorithm converge slowly.
  • Slow Convergence: Gradient Descent may require more iterations to converge to the minimum since it updates the parameters for each training example one at a time.
  • Local Minima: Gradient Descent can get stuck in local minima if the cost function has multiple local minima.
  • Noisy updates: The updates in Gradient Descent are noisy and have a high variance, which can make the optimization process less stable and lead to oscillations around the minimum.

   Overall, Gradient Descent is a useful optimization algorithm for linear regression, but it has some limitations and requires careful tuning of the learning rate to ensure convergence.



Previous Article
Next Article

Similar Reads

Difference between Batch Gradient Descent and Stochastic Gradient Descent
In order to train a Linear Regression model, we have to learn some model parameters such as feature weights and bias terms. An approach to do the same is Gradient Descent which is an iterative optimization algorithm capable of tweaking the model parameters by minimizing the cost function over the train data. It is a complete algorithm i.e it is gua
5 min read
Optimization techniques for Gradient Descent
Gradient Descent is a widely used optimization algorithm for machine learning models. However, there are several optimization techniques that can be used to improve the performance of Gradient Descent. Here are some of the most popular optimization techniques for Gradient Descent: Learning Rate Scheduling: The learning rate determines the step size
4 min read
ML | Mini-Batch Gradient Descent with Python
In machine learning, gradient descent is an optimization technique used for computing the model parameters (coefficients and bias) for algorithms like linear regression, logistic regression, neural networks, etc. In this technique, we repeatedly iterate through the training set and update the model parameters in accordance with the gradient of the
5 min read
Difference between Gradient descent and Normal equation
In regression models, our objective is to discover a model that can make predictions that closely resemble the actual target values. Basically, we try to find the parameters of the model which support our objective of the best model. The general behind finding this parameter is that we calculate the error between our actual value and predicted valu
4 min read
Vectorization Of Gradient Descent
In Machine Learning, Regression problems can be solved in the following ways: 1. Using Optimization Algorithms - Gradient Descent Batch Gradient Descent.Stochastic Gradient Descent.Mini-Batch Gradient DescentOther Advanced Optimization Algorithms like ( Conjugate Descent ... ) 2. Using the Normal Equation : Using the concept of Linear Algebra. Let'
5 min read
How to implement a gradient descent in Python to find a local minimum ?
Gradient Descent is an iterative algorithm that is used to minimize a function by finding the optimal parameters. Gradient Descent can be applied to any dimension function i.e. 1-D, 2-D, 3-D. In this article, we will be working on finding global minima for parabolic function (2-D) and will be implementing gradient descent in python to find the opti
8 min read
Numpy Gradient - Descent Optimizer of Neural Networks
NumPy Gradient Descent Optimizer is a commonly used optimization algorithm in neural network training that is based on the gradient descent algorithm. It is used to minimize the cost function of a neural network model, by adjusting the model's weights and biases through a series of iterations. The basic steps of NumPy Gradient Descent Optimizer are
6 min read
Gradient Descent With RMSProp from Scratch
Gradient descent is an optimization algorithm used to find the set of parameters (coefficients) of a function that minimizes a cost function. This method iteratively adjusts the coefficients of the function until the cost reaches the local, or global, minimum. Gradient descent works by calculating the partial derivatives of the cost function with r
6 min read
How to Implement Adam Gradient Descent from Scratch using Python?
Grade descent is an extensively used optimization algorithm in machine literacy and deep literacy. It's used to minimize the cost or loss function of a model by iteratively confirming the model's parameters grounded on the slants of the cost function with respect to those parameters. One variant of gradient descent that has gained popularity is the
14 min read
ML | Stochastic Gradient Descent (SGD)
Gradient Descent is an iterative optimization process that searches for an objective function's optimum value (Minimum/Maximum). It is one of the most used methods for changing a model's parameters in order to reduce a cost function in machine learning projects.   The primary goal of gradient descent is to identify the model parameters that provide
10 min read
Stochastic Gradient Descent Regressor using Scikit-learn
Stochastic Gradient Descent (SGD) is a popular optimization technique in the field of machine learning. It is particularly well-suited for handling large datasets and online learning scenarios where data arrives sequentially. In this article, we will discuss how a stochastic gradient descent regressor is implemented using Scikit-Learn. What is a st
3 min read
Stochastic Gradient Descent In R
Gradient Descent is an iterative optimization process that searches for an objective function’s optimum value (Minimum/Maximum). It is one of the most used methods for changing a model’s parameters to reduce a cost function in machine learning projects. In this article, we will learn the concept of SGD and its implementation in the R Programming La
10 min read
Applications of Derivatives in Machine Learning: From Gradient Descent to Probabilistic Models
Derivatives are fundamental concepts in calculus that measure how a function changes as its input changes. In machine learning, derivatives play a crucial role in various aspects, optimization algorithms, training models, and improving the performance of various machine learning techniques. This article explores the applications of derivatives in m
7 min read
Different Variants of Gradient Descent
Gradient descent is a fundamental optimization algorithm in machine learning, used to minimize functions by iteratively moving towards the minimum. It's crucial for training models by fine-tuning parameters to reduce prediction errors. The article aims to explore the fundamentals of different variants of Gradient Descent along with their advantages
11 min read
Gradient Descent Algorithm in Machine Learning
Think about how a machine learns from the data in machine learning and deep learning during training.  This involves a large amount of data. Through the lens of this article, we will delve into the intricacies of minimizing the cost function, a pivotal task in training models. Table of Content Gradient Descent in Machine LearningGradient Descent Py
15+ min read
Gradient Boosting for Linear Regression: Enhancing Predictive Accuracy
Linear regression is a fundamental technique in machine learning and statistics used to model the relationship between a dependent variable and one or more independent variables. However, traditional linear regression methods can be limited in their ability to handle complex data sets and non-linear relationships. This is where gradient boosting, a
6 min read
ML | Linear Regression vs Logistic Regression
Linear Regression is a machine learning algorithm based on supervised regression algorithm. Regression models a target prediction value based on independent variables. It is mostly used for finding out the relationship between variables and forecasting. Different regression models differ based on – the kind of relationship between the dependent and
3 min read
The Difference between Linear Regression and Nonlinear Regression Models
areRegression analysis is a fundamental tool in statistical modelling used to understand the relationship between a dependent variable and one or more independent variables. Two primary types of regression models are linear regression and nonlinear regression. This article delves into the key differences between these models, their applications, an
7 min read
Support Vector Regression (SVR) using Linear and Non-Linear Kernels in Scikit Learn
Support vector regression (SVR) is a type of support vector machine (SVM) that is used for regression tasks. It tries to find a function that best predicts the continuous output value for a given input value. SVR can use both linear and non-linear kernels. A linear kernel is a simple dot product between two input vectors, while a non-linear kernel
5 min read
How to improve the performance of segmented regression using quantile regression in R?
Segmented regression, also known as piecewise or broken-line regression is a powerful statistical technique used to identify changes in the relationship between a dependent variable and one or more independent variables. Quantile regression, on the other hand, estimates the conditional quantiles of a response variable distribution in the linear mod
8 min read
Multiple Linear Regression using R
Prerequisite: Simple Linear-Regression using RLinear Regression: It is the basic and commonly used type for predictive analysis. It is a statistical approach for modeling the relationship between a dependent variable and a given set of independent variables.These are of two types: Simple linear RegressionMultiple Linear Regression Let's Discuss Mul
3 min read
Linear Regression using PyTorch
Linear Regression is a very commonly used statistical method that allows us to determine and study the relationship between two continuous variables. The various properties of linear regression and its Python implementation have been covered in this article previously. Now, we shall find out how to implement this in PyTorch, a very popular deep lea
4 min read
Mathematical explanation for Linear Regression working
Suppose we are given a dataset: Given is a Work vs Experience dataset of a company and the task is to predict the salary of a employee based on his / her work experience. This article aims to explain how in reality Linear regression mathematically works when we use a pre-defined function to perform prediction task. Let us explore how the stuff work
1 min read
ML | Boston Housing Kaggle Challenge with Linear Regression
Boston Housing Data: This dataset was taken from the StatLib library and is maintained by Carnegie Mellon University. This dataset concerns the housing prices in the housing city of Boston. The dataset provided has 506 instances with 13 features.The Description of the dataset is taken from the below reference as shown in the table follows: Let's ma
3 min read
ML | Normal Equation in Linear Regression
We know the Linear Regression model is a parameterized model which means that the model's behavior and predictions are determined by a set of parameters or coefficients in the model. However, we use different methods for finding these parameters which give the lowest error on our dataset. In this article, we will read one such article which is the
4 min read
ML | Locally weighted Linear Regression
Linear Regression is a supervised learning algorithm used for computing linear relationships between input (X) and output (Y). The steps involved in ordinary linear regression are: Training phase: Compute [Tex]\theta [/Tex]to minimize the cost. [Tex]J(\theta) = $\sum_{i=1}^{m} (\theta^Tx^{(i)} - y^{(i)})^2 [/Tex] Predict output: for given query poi
3 min read
ML | Multiple Linear Regression using Python
Linear Regression: It is the basic and commonly used type for predictive analysis. It is a statistical approach to modeling the relationship between a dependent variable and a given set of independent variables. These are of two types: Simple linear RegressionMultiple Linear Regression Let's Discuss Multiple Linear Regression using Python. Multiple
6 min read
ML | Multiple Linear Regression (Backward Elimination Technique)
Multiple Linear Regression is a type of regression where the model depends on several independent variables(instead of only on one independent variable as seen in the case of Simple Linear Regression). Multiple Linear Regression has several techniques to build an effective model namely: All-in Backward Elimination Forward Selection Bidirectional El
5 min read
Pyspark | Linear regression with Advanced Feature Dataset using Apache MLlib
Ames Housing Data: The Ames Housing dataset was compiled by Dean De Cock for use in data science education and expanded version of the often-cited Boston Housing dataset. The dataset provided has 80 features and 1459 instances. Dataset description is as below: For demo few columns are displayed but there are a lot more columns are there in the data
4 min read
Polynomial Regression for Non-Linear Data - ML
Non-linear data is usually encountered in daily life. Consider some of the equations of motion as studied in physics. Projectile Motion: The height of a projectile is calculated as h = -½ gt2 +ut +ho Equation of motion under free fall: The distance travelled by an object after falling freely under gravity for ‘t’ seconds is ½ g t2. Distance travell
5 min read
Article Tags :
Practice Tags :