⚡️ Let's learn how to code very simple neural network with #PyTorch
It is not something state-of-the-art but very basic model to give you idea how to make actual #MachineLearning model.
Thread 🧵
Let's learn about using API for most common tasks with #PyTorch (Note: Code of this thread is via official docs)
So, Let's build simple classifier with #PyTorch (Language: #Python)
First, we need to import required libraries.
Note: For different kinds of #data, #torch provide TorchVision, TorchText and TorchAudio.
Here, we will be using image data.
Let's load data now.
As torch provides various #datasets, you can use datasets like #MNIST, #coco etc. directly without downloading them externally.
All included datasets have two args: "transform" and "target_transform". They modify samples and labels respectively.
We need to wrap dataset in DataLoader object to make it iterable. We select batch size to 32 here but you can go with any reasonable number.
You can check shape of dataloaders with this:
Now crucial part, we are creating #model and in #PyTorch, we create class which inherits from "nn.Module".
Layers of network goes into "__init__" function. The order of layers in forward pass is written in "forward" function.
We are checking GPU availibility at the start.
Now, let's code training part for which, we need #optimizer and #loss function. #PyTorch provides us with code directly from #library.
We are writing #training function now where model make prediction, compare it with ground truth and make adjustments as per difference between predicted class and ground truth.
We need to test model for test dataset too. We will write separate function for the same. Note that we are not supposed to get #optimizer here as this part does not contribute to training.
Now, we run actual training for 5 epochs. Results are not great but we haven't optimized our network plus number of epochs is also small but high accuracy was not target of this experiment (maybe one more thread for same).
Now, we cannot train model every time so we save model for future usage of same. It just take couple of lines to save trained model.
Now, we can load saved model and use the same for prediction. Let's first see how to load model created in #PyTorch
Now, for final part, we will use saved model to make actual prediction on data, this is how it can be done with just few lines of code with #PyTorch
Congratulations 🥳! You created, trained and used entire neural network with #PyTorch. It was really easy all thanks to creators of #PyTorch. You can literally code neural network without knowing all complex math behind it.