Linear regression using PyTorch

| | | | | | | | | | | | | | | | | | | |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

First, you will need to install PyTorch in your Python environment. The easiest way to do this is — use the pip or conda tool. Visit pytorch.org and install the version of your Python interpreter and package manager that you would like to use.

# We can run this Python code on a Jupyter notebook
# to automatically install the correct version
# 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 - 0.3 . 0.post4 - {platform} - linux_x86_64.whl torchvision

With PyTorch installed, let’s now look at the code.
Write the two lines below to import the required library functions and objects.

import torch

from torch.autograd import Variable

We also define some data and assign it to the variables x_data and y_data, as follows:

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 — our independent variable, and y_data — our dependent variable. This will be our dataset for now. Next, we need to define our model. There are two main steps involved in defining our model. They are:

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

We use the class below:

class LinearRegressionModel (torch.nn.Module):

def __ init __ ( self ):

super (LinearRegressionModel, self ) .__ init __ ()

self . linear = torch.nn.Linear ( 1 , 1 ) # One input and one exit

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 . In addition, since we only have one input and one output here, we use a linear model with an input and output size of 1.

Next, we create an object of this model.

# our model

our_model = LinearRegressionModel ()

After that choose an optimizer and loss criteria. Here we will use mean squared error (MSE) as our loss function and Stochastic Gradient Descent (SGD) as our optimizer. We also arbitrarily fix the learning rate to 0.01.

criterion = torch.nn.MSELoss (size_average = False )

optimizer = torch.optim.SGD (our_model.parameters (), lr = 0.01 )

Now we come to our learning stage. We perform the following tasks 500 times during training:

  1. Perform a live transfer by passing in our data and figuring out the predicted y value.
  2. Calculate loss using MSE.
  3. Reset all gradients to 0, back propagate and then update the weights.

for epoch in range ( 500 ):

# Forward pass: compute predicted y by passing

#x to the model

pred_y = our_model (x_data)

# Calculate and lose print

loss = criterion (pred_y, y_data)

# Zero gradients, backtrack

# and update the weight.

optimizer.zero_grad ()

loss.backward ()

optimizer.step ()

print ( ’ epoch {}, loss {} ’ . format (epoch, loss.data [ 0 ]))

After completing the training we check if we are getting the correct results using the model that we have defined. So we check it for an unknown x_data value, in this case 4.0.

new_var = Variable (torch.Tensor ([[[ 4.0 ] ]))

pred_y = our_model ( new_var)

print ( "predict ( after training) " , 4 , our_model (new_var) .data [ 0 ] [ 0 ])

If you followed all the steps correctly, you you will see that for entry 4.0 you get a value very close to 8.0, as shown below. Thus, our model essentially learns the relationship between input and output without explicit programming.

predict (after training) 4 7.966438293457031

For reference, you can find all the code for this article below:

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 input and one output

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

# —Ö to model

pred_y = our_model (x_data)

# Calculate and lose print

loss = criterion (pred_y, y_data)

# Zero gradients, back pass,

# and update the weight.

optimizer.zero_grad ()

loss.backward ()

optimizer.step ()

print ( ’epoch {}, loss {}’ . format (epoch, loss.data [ 0 ]))

new_var = Variable (torch.Tensor ([[ 4.0 ]]))

pred_y = our_model (new_var)

print ( "predict (after training)" , 4 , our_model (new_var) .data [ 0 ] [ 0 ])

Links

👻 Read also: what is the best laptop for engineering students?

Linear regression using PyTorch __del__: Questions

How can I make a time delay in Python?

5 answers

I would like to know how to put a time delay in a Python script.

2973

Answer #1

import time
time.sleep(5)   # Delays for 5 seconds. You can also use a float value.

Here is another example where something is run approximately once a minute:

import time
while True:
    print("This prints once a minute.")
    time.sleep(60) # Delay for 1 minute (60 seconds).

2973

Answer #2

You can use the sleep() function in the time module. It can take a float argument for sub-second resolution.

from time import sleep
sleep(0.1) # Time in seconds

Linear regression using PyTorch __del__: Questions

How to delete a file or folder in Python?

5 answers

How do I delete a file or folder in Python?

2639

Answer #1


Path objects from the Python 3.4+ pathlib module also expose these instance methods:

We hope this article has helped you to resolve the problem. Apart from Linear regression using PyTorch, check other __del__-related topics.

Want to excel in Python? See our review of the best Python online courses 2023. If you are interested in Data Science, check also how to learn programming in R.

By the way, this material is also available in other languages:



Dmitry Lehnman

Shanghai | 2023-01-31

Maybe there are another answers? What Linear regression using PyTorch exactly means?. Checked yesterday, it works!

Olivia Nickolson

Munchen | 2023-01-31

Simply put and clear. Thank you for sharing. Linear regression using PyTorch and other issues with StackOverflow was always my weak point 😁. Checked yesterday, it works!

Carlo Danburry

Berlin | 2023-01-31

I was preparing for my coding interview, thanks for clarifying this - Linear regression using PyTorch in Python is not the simplest one. Checked yesterday, it works!

Shop

Gifts for programmers

Learn programming in R: courses

$FREE
Gifts for programmers

Best Python online courses for 2022

$FREE
Gifts for programmers

Best laptop for Fortnite

$399+
Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best computer for crypto mining

$499+
Gifts for programmers

Best laptop for Sims 4

$

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically