# These are the libraries will be used for this lab.
import numpy as np
import matplotlib.pyplot as plt
Linear Regression 1D, Training One Parameter
Linear Regression 1D: Training One Parameter
Objective
- How to create cost or criterion function using MSE (Mean Square Error).
Table of Contents
In this lab, you will train a model with PyTorch by using data that you created. The model only has one parameter: the slope.
Estimated Time Needed: 20 min
Preparation
The following are the libraries we are going to use for this lab.
The class plot_diagram
helps us to visualize the data space and the parameter space during training and has nothing to do with PyTorch.
# The class for plotting
class plot_diagram():
# Constructor
def __init__(self, X, Y, w, stop, go = False):
= w.data
start self.error = []
self.parameter = []
self.X = X.numpy()
self.Y = Y.numpy()
self.parameter_values = torch.arange(start, stop)
self.Loss_function = [criterion(forward(X), Y) for w.data in self.parameter_values]
= start
w.data
# Executor
def __call__(self, Yhat, w, error, n):
self.error.append(error)
self.parameter.append(w.data)
212)
plt.subplot(self.X, Yhat.detach().numpy())
plt.plot(self.X, self.Y,'ro')
plt.plot("A")
plt.xlabel(-20, 20)
plt.ylim(211)
plt.subplot("Data Space (top) Estimated Line (bottom) Iteration " + str(n))
plt.title(self.parameter_values.numpy(), self.Loss_function)
plt.plot(self.parameter, self.error, 'ro')
plt.plot("B")
plt.xlabel(
plt.figure()
# Destructor
def __del__(self):
'all') plt.close(
Make Some Data
Import PyTorch library:
# Import the library PyTorch
import torch
Generate values from -3 to 3 that create a line with a slope of -3. This is the line you will estimate.
# Create the f(X) with a slope of -3
= torch.arange(-3, 3, 0.1).view(-1, 1)
X = -3 * X f
Let us plot the line.
# Plot the line with blue
= 'f')
plt.plot(X.numpy(), f.numpy(), label 'x')
plt.xlabel('y')
plt.ylabel(
plt.legend() plt.show()
Let us add some noise to the data in order to simulate the real data. Use torch.randn(X.size())
to generate Gaussian noise that is the same size as X
and has a standard deviation opf 0.1.
# Add some noise to f(X) and save it in Y
= f + 0.1 * torch.randn(X.size()) Y
Plot the Y
:
# Plot the data points
'rx', label = 'Y')
plt.plot(X.numpy(), Y.numpy(),
= 'f')
plt.plot(X.numpy(), f.numpy(), label 'x')
plt.xlabel('y')
plt.ylabel(
plt.legend() plt.show()
Create the Model and Cost Function (Total Loss)
In this section, let us create the model and the cost function (total loss) we are going to use to train the model and evaluate the result.
First, define the forward
function \(y=w*x\). (We will add the bias in the next lab.)
# Create forward function for prediction
def forward(x):
return w * x
Define the cost or criterion function using MSE (Mean Square Error):
# Create the MSE function for evaluate the result.
def criterion(yhat, y):
return torch.mean((yhat - y) ** 2)
Define the learning rate lr
and an empty list LOSS
to record the loss for each iteration:
# Create Learning Rate and an empty list to record the loss for each iteration
= 0.1
lr = [] LOSS
Now, we create a model parameter by setting the argument requires_grad
to True
because the system must learn it.
= torch.tensor(-10.0, requires_grad = True) w
Create a plot_diagram
object to visualize the data space and the parameter space for each iteration during training:
= plot_diagram(X, Y, w, stop = 5) gradient_plot
Train the Model
Let us define a function for training the model. The steps will be described in the comments.
# Define a function for train the model
def train_model(iter):
for epoch in range (iter):
# make the prediction as we learned in the last lab
= forward(X)
Yhat
# calculate the iteration
= criterion(Yhat,Y)
loss
# plot the diagram for us to have a better idea
# gradient_plot(Yhat, w, loss.item(), epoch)
# store the loss into list
LOSS.append(loss.item())
# backward pass: compute gradient of the loss with respect to all the learnable parameters
loss.backward()
# updata parameters
= w.data - lr * w.grad.data
w.data
# zero the gradients before running the backward pass
w.grad.data.zero_()
Let us try to run 4 iterations of gradient descent:
# Give 4 iterations for training the model here.
4) train_model(
Plot the cost for each iteration:
# Plot the loss for each iteration
plt.plot(LOSS)
plt.tight_layout()"Epoch/Iterations")
plt.xlabel("Cost") plt.ylabel(
Text(38.347222222222214, 0.5, 'Cost')