1D Regression
title: Linear Regression 1D, Prediction author: Juma Shafara date: "2023-09" date-modified: "2024-07-30" description: In this lab, we will review how to make a prediction in several different ways by using PyTorch. keywords: []

Objective
- How to make the prediction for multiple inputs.
- How to use linear class to build more complex models.
- How to build a custom module.
Table of Contents
In this lab, we will review how to make a prediction in several different ways by using PyTorch.
Estimated Time Needed: 15 min
Preparation
The following are the libraries we are going to use for this lab.
Prediction
Let us create the following expressions:
\(b=-1,w=2\)
\(\hat{y}=-1+2x\)
First, define the parameters:
Then, define the function forward(x, w, b) makes the prediction:
Let's make the following prediction at x = 1
\(\hat{y}=-1+2x\)
\(\hat{y}=-1+2(1)\)
Now, let us try to make the prediction for multiple inputs:

Let us construct the x tensor first. Check the shape of x.
Now make the prediction:
The result is the same as what it is in the image above.
Practice
Make a prediction of the following x tensor using the w and b from above.
Double-click here for the solution.
Class Linear
The linear class can be used to make a prediction. We can also use the linear class to build more complex models. Let's import the module:
Set the random seed because the parameters are randomly initialized:
Let us create the linear object by using the constructor. The parameters are randomly created. Let us print out to see what w and b. The parameters of an torch.nn.Module model are contained in the model’s parameters accessed with lr.parameters():
This is equivalent to the following expression:
\(b=-0.44, w=0.5153\)
\(\hat{y}=-0.44+0.5153x\)
A method state_dict() Returns a Python dictionary object corresponding to the layers of each parameter tensor.
The keys correspond to the name of the attributes and the values correspond to the parameter value.
Now let us make a single prediction at x = [[1.0]].
Similarly, you can make multiple predictions:

Use model lr(x) to predict the result.
Practice
Make a prediction of the following x tensor using the linear regression model lr.
Double-click here for the solution.
Build Custom Modules
Now, let's build a custom module. We can make more complex models by using this method later on.
First, import the following library.
Now, let us define the class:
Create an object by using the constructor. Print out the parameters we get and the model.
Let us try to make a prediction of a single input sample.
Now, let us try another example with multiple samples.
the parameters are also stored in an ordered dictionary :
Practice
Create an object lr1 from the class we created before and make a prediction by using the following tensor: