In this tutorial we will implement a simple neural network from scratch using PyTorch. The idea of the tutorial is to teach you the basics of PyTorch and how it can be used to implement a neural network from scratch. I will go over some of the basic functionalities and concepts available in PyTorch that will allow you to build your own neural networks.
This tutorial assumes you have prior knowledge of how a neural network works. Don’t worry! Even if you are not so sure, you will be okay. For advanced PyTorch users, this tutorial may still serve as a refresher. This tutorial is heavily inspired by this Neural Network implementation coded purely using Numpy. In fact, I tried re-implementing the code using PyTorch instead and added my own intuitions and explanations. Thanks to Samay for his phenomenal work, I hope this inspires many others as it did with me.
torch module provides all the necessary tensor operators you will need to implement your first neural network from scratch in PyTorch. That's right! In PyTorch everything is a Tensor, so this is the first thing you will need to get used to. Let's import the libraries we will need for this tutorial.
import torch import torch.nn as nn
Let's start by creating some sample data using the
torch.tensor command. In Numpy, this could be done with
np.array. Both functions serve the same purpose, but in PyTorch everything is a Tensor as opposed to a vector or matrix. We define types in PyTorch using the
In the data below,
X represents the amount of hours studied and how much time students spent sleeping, whereas
y represent grades. The variable
xPredicted is a single input for which we want to predict a grade using the parameters learned by the neural network. Remember, the neural network wants to learn a mapping between
y, so it will try to take a guess from what it has learned from the training data.
X = torch.tensor(([2, 9], [1, 5], [3, 6]), dtype=torch.float) # 3 X 2 tensor y = torch.tensor((, , ), dtype=torch.float) # 3 X 1 tensor xPredicted = torch.tensor(([4, 8]), dtype=torch.float) # 1 X 2 tensor
You can check the size of the tensors we have just created with the
size command. This is equivalent to the
shape command used in tools such as Numpy and Tensorflow.
torch.Size([3, 2]) torch.Size([3, 1])
Below we are performing some scaling on the sample data. Notice that the
max function returns both a tensor and the corresponding indices. So we use
_ to capture the indices which we won't use here because we are only interested in the max values to conduct the scaling. Perfect! Our data is now in a very nice format our neural network will appreciate later on.
# scale units X_max, _ = torch.max(X, 0) xPredicted_max, _ = torch.max(xPredicted, 0) X = torch.div(X, X_max) xPredicted = torch.div(xPredicted, xPredicted_max) y = y / 100 # max test score is 100 print(xPredicted)
Notice that there are two functions
div that I didn't discuss above. They do exactly what they imply:
max finds the maximum value in a vector... I mean tensor; and
div is basically a nice little function to divide two tensors.
Once the data has been processed and it is in the proper format, all you need to do now is to define your model. Here is where things begin to change a little as compared to how you would build your neural networks using, say, something like Keras or Tensorflow. However, you will realize quickly as you go along that PyTorch doesn't differ much from other deep learning tools. At the end of the day we are constructing a computation graph, which is used to dictate how data should flow and what type of operations are performed on this information.
For illustration purposes, we are building the following neural network or computation graph:
class Neural_Network(nn.Module): def __init__(self, ): super(Neural_Network, self).__init__() # parameters # TODO: parameters can be parameterized instead of declaring them here self.inputSize = 2 self.outputSize = 1 self.hiddenSize = 3 # weights self.W1 = torch.randn(self.inputSize, self.hiddenSize) # 3 X 2 tensor self.W2 = torch.randn(self.hiddenSize, self.outputSize) # 3 X 1 tensor def forward(self, X): self.z = torch.matmul(X, self.W1) # 3 X 3 ".dot" does not broadcast in PyTorch self.z2 = self.sigmoid(self.z) # activation function self.z3 = torch.matmul(self.z2, self.W2) o = self.sigmoid(self.z3) # final activation function return o def sigmoid(self, s): return 1 / (1 + torch.exp(-s)) def sigmoidPrime(self, s): # derivative of sigmoid return s * (1 - s) def backward(self, X, y, o): self.o_error = y - o # error in output self.o_delta = self.o_error * self.sigmoidPrime(o) # derivative of sig to error self.z2_error = torch.matmul(self.o_delta, torch.t(self.W2)) self.z2_delta = self.z2_error * self.sigmoidPrime(self.z2) self.W1 += torch.matmul(torch.t(X), self.z2_delta) self.W2 += torch.matmul(torch.t(self.z2), self.o_delta) def train(self, X, y): # forward + backward pass for training o = self.forward(X) self.backward(X, y, o) def saveWeights(self, model): # we will use the PyTorch internal storage functions torch.save(model, "NN") # you can reload model with all the weights and so forth with: # torch.load("NN") def predict(self): print ("Predicted data based on trained weights: ") print ("Input (scaled): \n" + str(xPredicted)) print ("Output: \n" + str(self.forward(xPredicted)))
For the purpose of this tutorial, we are not going to be talking math stuff, that's for another day. I just want you to get a gist of what it takes to build a neural network from scratch using PyTorch. Let's break down the model which was declared via the class above.
First, we defined our model via a class because that is the recommended way to build the computation graph. The class header contains the name of the class
Neural Network and the parameter
nn.Module which basically indicates that we are defining our own neural network.
The next step is to define the initializations (
def __init__(self,)) that will be performed upon creating an instance of the customized neural network. You can declare the parameters of your model here, but typically, you would declare the structure of your network in this section -- the size of the hidden layers and so forth. Since we are building the neural network from scratch, we explicitly declared the size of the weights matrices: one that stores the parameters from the input to hidden layer; and one that stores the parameter from the hidden to output layer. Both weight matrices are initialized with values randomly chosen from a normal distribution via
torch.randn(...). Note that we are not using bias just to keep things as simple as possible.
def __init__(self, ): super(Neural_Network, self).__init__() # parameters # TODO: parameters can be parameterized instead of declaring them here self.inputSize = 2 self.outputSize = 1 self.hiddenSize = 3 # weights self.W1 = torch.randn(self.inputSize, self.hiddenSize) # 3 X 2 tensor self.W2 = torch.randn(self.hiddenSize, self.outputSize) # 3 X 1 tensor
forward function is where all the magic happens (see below). This is where the data enters and is fed into the computation graph (i.e., the neural network structure we have built). Since we are building a simple neural network with one hidden layer, our forward function looks very simple:
def forward(self, X): self.z = torch.matmul(X, self.W1) self.z2 = self.sigmoid(self.z) # activation function self.z3 = torch.matmul(self.z2, self.W2) o = self.sigmoid(self.z3) # final activation function return o
forward function above takes the input
Xand then performs a matrix multiplication (
torch.matmul(...)) with the first weight matrix
self.W1. Then the result is applied an activation function,
sigmoid. The resulting matrix of the activation is then multiplied with the second weight matrix
self.W2. Then another activation if performed, which renders the output of the neural network or computation graph. The process I described above is simply what's known as a
feedforward pass. In order for the weights to optimize when training, we need a backpropagation algorithm.
backward function contains the backpropagation algorithm, where the goal is to essentially minimize the loss with respect to our weights. In other words, the weights need to be updated in such a way that the loss decreases while the neural network is training (well, that is what we hope for). All this magic is possible with the gradient descent algorithm which is declared in the
backward function. Take a minute or two to inspect what is happening in the code below:
def backward(self, X, y, o): self.o_error = y - o # error in output self.o_delta = self.o_error * self.sigmoidPrime(o) self.z2_error = torch.matmul(self.o_delta, torch.t(self.W2)) self.z2_delta = self.z2_error * self.sigmoidPrime(self.z2) self.W1 += torch.matmul(torch.t(X), self.z2_delta) self.W2 += torch.matmul(torch.t(self.z2), self.o_delta)
Notice that we are performing a lot of matrix multiplications along with the transpose operations via the
torch.t(...) operations, respectively. The rest is simply gradient descent -- there is nothing to it.
All that is left now is to train the neural network. First we create an instance of the computation graph we have just built:
NN = Neural_Network()
Then we train the model for
1000 rounds. Notice that in PyTorch
NN(X) automatically calls the
forward function so there is no need to explicitly call
After we have obtained the predicted output for ever round of training, we compute the loss, with the following code:
torch.mean((y - NN(X))**2).detach().item()
The next step is to start the training (foward + backward) via
NN.train(X, y). After we have trained the neural network, we can store the model and output the predicted value of the single instance we declared in the beginning,
NN = Neural_Network() for i in range(1000): # trains the NN 1,000 times if (i % 100) == 0: print ("#" + str(i) + " Loss: " + str(torch.mean((y - NN(X))**2).detach().item())) # mean sum squared loss NN.train(X, y) NN.saveWeights(NN) NN.predict() print("Finished training!")
#0 Loss: 0.24544493854045868 #100 Loss: 0.0026628002524375916 #200 Loss: 0.0024748605210334063 #300 Loss: 0.002363199135288596 #400 Loss: 0.0022466194350272417 #500 Loss: 0.0021235516760498285 #600 Loss: 0.001996910898014903 #700 Loss: 0.0018705682596191764 #800 Loss: 0.0017485078424215317 #900 Loss: 0.0016340742586180568 Predicted data based on trained weights: Input (scaled): tensor([0.5000, 1.0000]) Output: tensor([0.9529]) Finished training!
/usr/local/lib/python3.6/dist-packages/torch/serialization.py:360: UserWarning: Couldn't retrieve source code for container of type Neural_Network. It won't be checked for correctness upon loading. "type " + obj.__name__ + ". It won't be checked "
The loss keeps decreasing, which means that the neural network is learning something. That's it. Congratulations! You have just learned how to create and train a neural network from scratch using PyTorch. There are so many things you can do with the shallow network we have just implemented. You can add more hidden layers or try to incorporate the bias terms for practice. I would love to see what you will build from here. Reach me out on Twitter if you have any further questions or leave your comments here. Until next time!