<jupyter_start><jupyter_text>Linear Regression 1D: Training One Parameter Table of ContentsIn this lab, you will train a model with PyTorch by using data that you created. The model only has one parameter: the slope.    Make Some Data    Create the Model and Cost Function (Total Loss)    Train the ModelEstimated Time Needed: 20 min Preparation The following are the libraries we are going to use for this lab.<jupyter_code># These are the libraries will be used for this lab.

import numpy as np
import matplotlib.pyplot as plt<jupyter_output><empty_output><jupyter_text>The class plot_diagram helps us to visualize the data space and the parameter space during training and has nothing to do with PyTorch.<jupyter_code># The class for plotting

class plot_diagram():
    
    # Constructor
    def __init__(self, X, Y, w, stop, go = False):
        start = w.data
        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] 
        w.data = start
        
    # Executor
    def __call__(self, Yhat, w, error, n):
        self.error.append(error)
        self.parameter.append(w.data)
        plt.subplot(212)
        plt.plot(self.X, Yhat.detach().numpy())
        plt.plot(self.X, self.Y,'ro')
        plt.xlabel("A")
        plt.ylim(-20, 20)
        plt.subplot(211)
        plt.title("Data Space (top) Estimated Line (bottom) Iteration " + str(n))
        plt.plot(self.parameter_values.numpy(), self.Loss_function)   
        plt.plot(self.parameter, self.error, 'ro')
        plt.xlabel("B")
        plt.figure()
    
    # Destructor
    def __del__(self):
        plt.close('all')<jupyter_output><empty_output><jupyter_text>Make Some Data Import PyTorch library:<jupyter_code># Import the library PyTorch

import torch<jupyter_output><empty_output><jupyter_text>Generate values from -3 to 3 that create a line with a slope of -3. This is the line you will estimate.<jupyter_code># Create the f(X) with a slope of -3

X = torch.arange(-3, 3, 0.1).view(-1, 1)
f = -3 * X<jupyter_output><empty_output><jupyter_text>Let us plot the line.<jupyter_code># Plot the line with blue

plt.plot(X.numpy(), f.numpy(), label = 'f')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()<jupyter_output><empty_output><jupyter_text>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.<jupyter_code># Add some noise to f(X) and save it in Y

Y = f + 0.1 * torch.randn(X.size())<jupyter_output><empty_output><jupyter_text>Plot the Y:<jupyter_code># Plot the data points

plt.plot(X.numpy(), Y.numpy(), 'rx', label = 'Y')

plt.plot(X.numpy(), f.numpy(), label = 'f')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()<jupyter_output><empty_output><jupyter_text>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.)<jupyter_code># Create forward function for prediction

def forward(x):
    return w * x<jupyter_output><empty_output><jupyter_text>Define the cost or criterion function using MSE (Mean Square Error):<jupyter_code># Create the MSE function for evaluate the result.

def criterion(yhat, y):
    return torch.mean((yhat - y) ** 2)<jupyter_output><empty_output><jupyter_text>Define the learning rate lr and an empty list LOSS to record the loss for each iteration:<jupyter_code># Create Learning Rate and an empty list to record the loss for each iteration

lr = 0.1
LOSS = []<jupyter_output><empty_output><jupyter_text>Now, we create a model parameter by setting the argument requires_grad to  True because the system must learn it.<jupyter_code>w = torch.tensor(-10.0, requires_grad = True)<jupyter_output><empty_output><jupyter_text>Create a plot_diagram object to visualize the data space and the parameter space for each iteration during training:<jupyter_code>gradient_plot = plot_diagram(X, Y, w, stop = 5)<jupyter_output><empty_output><jupyter_text>Train the Model Let us define a function for training the model. The steps will be described in the comments.<jupyter_code># 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
        Yhat = forward(X)
        
        # calculate the iteration
        loss = criterion(Yhat,Y)
        
        # 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)
        
        # backward pass: compute gradient of the loss with respect to all the learnable parameters
        loss.backward()
        
        # updata parameters
        w.data = w.data - lr * w.grad.data
        
        # zero the gradients before running the backward pass
        w.grad.data.zero_()<jupyter_output><empty_output><jupyter_text>Let us try to run 4 iterations of gradient descent:<jupyter_code># Give 4 iterations for training the model here.

train_model(4)<jupyter_output><empty_output><jupyter_text>Plot the cost for each iteration:<jupyter_code># Plot the loss for each iteration

plt.plot(LOSS)
plt.tight_layout()
plt.xlabel("Epoch/Iterations")
plt.ylabel("Cost")<jupyter_output><empty_output><jupyter_text>Practice Create a new learnable parameter w with an initial value of -15.0.<jupyter_code># Practice: Create w with the inital value of -15.0

w = torch.tensor(-15.0, requires_grad=True)<jupyter_output><empty_output><jupyter_text>Create an empty list LOSS2:<jupyter_code># Practice: Create LOSS2 list
LOSS2 = []<jupyter_output><empty_output><jupyter_text>Write your own my_train_model function with loss list LOSS2. And run it with 4 iterations.<jupyter_code>def my_train_model(iter):
    for epoch in range (iter):
        Yhat = forward(X)
        loss = criterion(Yhat,Y)
        gradient_plot1(Yhat, w, loss.item(), epoch)
        LOSS2.append(loss)
        loss.backward()
        w.data = w.data - lr * w.grad.data
        w.grad.data.zero_()
my_train_model(4)
# Practice: Create your own my_train_model

gradient_plot1 = plot_diagram(X, Y, w, stop = 15)<jupyter_output><empty_output><jupyter_text>Plot an overlay of the list LOSS2 and LOSS.<jupyter_code># Practice: Plot the list LOSS2 and LOSS

plt.plot(LOSS, label = "LOSS")
plt.plot(LOSS2, label = "LOSS2")
plt.tight_layout()
plt.xlabel("Epoch/Iterations")
plt.ylabel("Cost")
plt.legend()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10167499265354099, 'fraction_numerical': 0.00910960916838084, 'mean_word_length': 3.841394025604552, 'pattern_counts': {'":': 0, '<': 77, '<?xml version=': 0, '>': 77, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '19', 'dir': 'jupyter-structured-clean-dedup', 'id': '129836', 'license': 'MIT', 'n_tokens_mistral': 2299, 'n_tokens_neox': 2197, 'n_words': 708, 'path': '2. LinearRegression/2.2.1linear_regression_one_parameter_v2.ipynb', 'repo_name': 'Niranjankumar-c/DeepLearning-Pytorch-IBM', 'size': '6806'}