The Wayback Machine - https://web.archive.org/web/20241127035007/https://www.geeksforgeeks.org/linear-regression-using-pytorch/
Open In App

Linear Regression using PyTorch

Last Updated : 17 Sep, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 learning library that is being developed by Facebook.
Firstly, you will need to install PyTorch into your Python environment. The easiest way to do this is to use the pip or conda tool. Visit pytorch.org and install the version of your Python interpreter and the package manager that you would like to use. 
 

Python3




# We can run this Python code on a Jupyter notebook
# to automatically install the correct version of
# PyTorch.
 
# http://pytorch.org / from os import path
from wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tag
platform = '{}{}-{}'.format(get_abbr_impl(), get_impl_ver(), get_abi_tag())
 
accelerator = 'cu80' if path.exists('/opt / bin / nvidia-smi') else 'cpu'
 
! pip install -q http://download.pytorch.org / whl/{accelerator}/torch-1.3.1.post4-{platform}-linux_x86_64.whl torchvision


With PyTorch installed, let us now have a look at the code. 
Write the two lines given below to import the necessary library functions and objects. 
 

Python3




import torch
from torch.autograd import Variable


We also define some data and assign them to variables x_data and y_data as given below: 
 

Python3




x_data = Variable(torch.Tensor([[1.0], [2.0], [3.0]]))
y_data = Variable(torch.Tensor([[2.0], [4.0], [6.0]]))


Here, x_data is our independent variable and y_data is our dependent variable. This will be our dataset for now. Next, we need to define our model. There are two main steps associated with defining our model. They are: 
 

  1. Initializing our model.
  2. Declaring the forward pass.

We use the class given below: 
 

Python3




class LinearRegressionModel(torch.nn.Module):
 
    def __init__(self):
        super(LinearRegressionModel, self).__init__()
        self.linear = torch.nn.Linear(1, 1# One in and one out
 
    def forward(self, x):
        y_pred = self.linear(x)
        return y_pred


As you can see, our Model class is a subclass of torch.nn.module. Also, since here we have only one input and one output, we use a Linear model with both the input and output dimension as 1.
Next, we create an object of this model. 
 

Python3




# our model
our_model = LinearRegressionModel()


After this, we select the optimizer and the loss criteria. Here, we will use the mean squared error (MSE) as our loss function and stochastic gradient descent (SGD) as our optimizer. Also, we arbitrarily fix a learning rate of 0.01.
 

Python3




criterion = torch.nn.MSELoss(size_average = False)
optimizer = torch.optim.SGD(our_model.parameters(), lr = 0.01)


We now arrive at our training step. We perform the following tasks 500 times during training: 
 

  1. Perform a forward pass bypassing our data and finding out the predicted value of y.
  2. Compute the loss using MSE.
  3. Reset all the gradients to 0, perform a backpropagation and then, update the weights.

 

Python3




for epoch in range(500):
 
    # Forward pass: Compute predicted y by passing
    # x to the model
    pred_y = our_model(x_data)
 
    # Compute and print loss
    loss = criterion(pred_y, y_data)
 
    # Zero gradients, perform a backward pass,
    # and update the weights.
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    print('epoch {}, loss {}'.format(epoch, loss.item()))


Once the training is completed, we test if we are getting correct results using the model that we defined. So, we test it for an unknown value of x_data, in this case, 4.0. 
 

Python3




new_var = Variable(torch.Tensor([[4.0]]))
pred_y = our_model(new_var)
print("predict (after training)", 4, our_model(new_var).item())


If you performed all steps correctly, you will see that for input 4.0, you are getting a value that is very close to 8.0 as below. So, our model inherently learns the relationship between the input data and the output data without being programmed explicitly.
predict (after training) 4 7.966438293457031
For your reference, you can find the entire code of this article given below: 
 

Python3




import torch
from torch.autograd import Variable
 
x_data = Variable(torch.Tensor([[1.0], [2.0], [3.0]]))
y_data = Variable(torch.Tensor([[2.0], [4.0], [6.0]]))
 
 
class LinearRegressionModel(torch.nn.Module):
 
    def __init__(self):
        super(LinearRegressionModel, self).__init__()
        self.linear = torch.nn.Linear(1, 1# One in and one out
 
    def forward(self, x):
        y_pred = self.linear(x)
        return y_pred
 
# our model
our_model = LinearRegressionModel()
 
criterion = torch.nn.MSELoss(size_average = False)
optimizer = torch.optim.SGD(our_model.parameters(), lr = 0.01)
 
for epoch in range(500):
 
    # Forward pass: Compute predicted y by passing
    # x to the model
    pred_y = our_model(x_data)
 
    # Compute and print loss
    loss = criterion(pred_y, y_data)
 
    # Zero gradients, perform a backward pass,
    # and update the weights.
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    print('epoch {}, loss {}'.format(epoch, loss.item()))
 
new_var = Variable(torch.Tensor([[4.0]]))
pred_y = our_model(new_var)
print("predict (after training)", 4, our_model(new_var).item())


References



Previous Article
Next Article

Similar Reads

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
Is least squares regression the same as linear regression
Yes, Least squares regression and linear regression are closely related in machine learning, but they’re not quite the same. Linear regression is a type of predictive model that assumes a linear relationship between input features and the output variable. Least squares is a common method used to find the best-fitting line in linear regression by mi
2 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
Can linear regression be used for non linear data?
The short answer is no, linear regression isn’t effective on non-linear data without adjustments. However, by transforming the data or extending linear regression to handle curves, we can sometimes adapt it to non-linear situations. Linear regression is generally not suitable for non-linear data because it assumes a straight-line relationship betwe
3 min read
Identifying handwritten digits using Logistic Regression in PyTorch
Logistic Regression is a very commonly used statistical method that allows us to predict a binary output from a set of independent variables. The various properties of logistic 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 learning
7 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
Logistic Regression on MNIST with PyTorch
Logistic Regression Logistic Regression is also known as Binary Classification is one of the most popular Machine Learning Algorithms. It comes under Supervised Learning Classification Algorithms. It is used to predict the probability of the target label. By binary classification, it means that the model predicts the label either 0 or 1. The target
4 min read
Multinomial Logistic Regression with PyTorch
Logistic regression is a popular machine learning algorithm used for binary classification tasks. It models the probability of the output variable (also known as the dependent variable) given the input variables (also known as the independent variables). It is a linear algorithm that applies a logistic function to the output of a linear regression
11 min read
Classification using PyTorch linear function
In machine learning, prediction is a critical component. It is the process of using a trained model to make predictions on new data. PyTorch is an open-source machine learning library that allows developers to build and train neural networks. One common use case in PyTorch is using linear classifiers for prediction tasks. In this article, we will g
7 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
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
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
Linear Regression Implementation From Scratch using Python
Linear Regression is a supervised learning algorithm which is both a statistical and a machine learning algorithm. It is used to predict the real-valued output y based on the given input value x. It depicts the relationship between the dependent variable y and the independent variables xi ( or features ). The hypothetical function used for predicti
4 min read
Locally weighted linear Regression using Python
Locally weighted linear regression is the nonparametric regression methods that combine k-nearest neighbor based machine learning. It is referred to as locally weighted because for a query point the function is approximated on the basis of data near that and weighted because the contribution is weighted by its distance from the query point. Locally
4 min read
Multiple Linear Regression using R to predict housing prices
Predicting housing prices is a common task in the field of data science and statistics. Multiple Linear Regression is a valuable tool for this purpose as it allows you to model the relationship between multiple independent variables and a dependent variable, such as housing prices. In this article, we'll walk you through the process of performing M
12 min read
Python | Linear Regression using sklearn
Prerequisite: Linear Regression Linear Regression is a machine learning algorithm based on supervised learning. It performs a regression task. 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 –
3 min read
ML | Rainfall prediction using Linear regression
Rainfall prediction is a common application of machine learning, and linear regression is a simple and effective technique that can be used for this purpose. In this task, the goal is to predict the amount of rainfall based on historical data. Linear regression is a supervised learning algorithm that is used to model the relationship between a depe
7 min read
Linear Regression using Turicreate
Linear Regression is a method or approach for Supervised Learning.Supervised Learning takes the historical or past data and then train the model and predict the things according to the past results.Linear Regression comes from the word 'Linear' and 'Regression'.Regression concept deals with predicting the future using the past data.Linear means the
2 min read
Multiple linear regression using R for the Real estate data set
Multiple linear regression is widely used in machine learning and data science. In this article, We will discuss the Multiple linear regression by building a step-by-step project on a Real estate data set. Multiple linear regressionMultiple Linear Regression is a statistical method used to model the relationship between a dependent variable (or tar
9 min read
Step-by-Step Guide to Modeling Time Series Data Using Linear Regression
Time series data is a sequence of data points collected or recorded at specific time intervals. Modeling time series data is crucial in various fields such as finance, economics, environmental science, and many others. One of the simplest yet powerful methods to model time series data is using linear regression. This article will delve into the tec
6 min read
Reason for Using RMSE Instead of MSE in Linear Regression
Answer: RMSE is preferred over MSE in linear regression because it is in the same units as the response variable, making interpretation easier.In linear regression analysis, both the Mean Squared Error (MSE) and the Root Mean Squared Error (RMSE) serve as measures to evaluate model performance, specifically regarding how well the model predicts the
2 min read
Interpreting the results of Linear Regression using OLS Summary
This article is to tell you the whole interpretation of the regression summary table. There are many statistical softwares that are used for regression analysis like Matlab, Minitab, spss, R etc. but this article uses python. The Interpretation is the same for other tools as well. This article needs the basics of statistics including basic knowledg
6 min read
Box Office Revenue Prediction Using Linear Regression in ML
When a movie is produced then the director would certainly like to maximize his/her movie's revenue. But can we predict what will be the revenue of a movie by using its genre or budget information? This is exactly what we'll learn in this article, we will learn how to implement a machine learning algorithm that can predict a box office revenue by u
6 min read
Multi Dimensional Inputs in Pytorch Linear Method in Python
In PyTorch, the torch.nn.Linear class is a linear layer that applies a linear transformation to the input data. It is called linear transformation because it applies the linear equation. i.e [Tex]y = xA^{T}+b[/Tex] Here x : input data of one or more dimensionsA : weightb : bias syntax: torch.nn.Linear(in_features, out_features, bias=True, device=No
5 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 | 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 (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
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
three90RightbarBannerImg