- Building a neural network with PyTorch
- Passing data through network layers and observing changes in tensor dimensions
- Demonstrating the effect of ReLU activation
- Executing a full forward pass
- Inspecting model parameters
- Setting up loss functions and optimizers
- Preparing datasets and dataloaders
- Creating an image classification network
- Implementing training and validation loops
Building a Simple Neural Network in PyTorch
In PyTorch, you can construct a neural network by defining a class that inherits fromnn.Module. Typically, this class includes an __init__ method to define the layers and a forward method that outlines how data flows through these layers.
Below is an example of a simple neural network class, SimpleNeuralNetwork. This model contains an input layer, a hidden layer, and an output layer, all implemented as linear layers. To introduce non-linearity, a ReLU activation is applied after the input and hidden layers.
Passing Data Through Layers
It is helpful to mimic the forward pass through each layer individually to observe how the tensor dimensions transform through the network. The following code snippet demonstrates this process step-by-step:- 10 to 20 after the input layer.
- 20 to 15 after the hidden layer.
- 15 to 1 after the output layer, representing the model’s final prediction.
Demonstrating the Effect of ReLU Activation
The ReLU activation function zeros out negative values, adding non-linearity to the model. Here’s how you can examine the effect of the ReLU activation:The ReLU function is used to prevent the network from learning only linear relationships, which is essential for handling complex data patterns.
Mimicking a Full Forward Pass
To observe how data flows from input to output in one full forward pass, we can simulate the process and print both the input and the final output:Inspecting Model Parameters
Each layer of the neural network has associated weights and biases which are updated during training. You can inspect these parameters as shown below:Defining Loss Functions and Optimizers
Loss functions measure the discrepancy between the model’s predictions and the true labels, and optimizers adjust model parameters to minimize this loss. PyTorch provides built-in support for various loss functions and optimizers.Preparing the Dataset and DataLoader
For training, we will use the FashionMNIST dataset. We first define a set of transformations to normalize the image data, then create dataloaders for both training and validation.Creating an Image Classification Neural Network
Below is an example that illustrates how to set up an image classification neural network. This example uses a simple structure similar to our previous model. In real scenarios, convolutional networks are more appropriate for image data.For demonstration, we will reuse our
SimpleNeuralNetwork class. In practice, you would define a convolutional architecture for image classification tasks.Training and Validation Loop
Implementing a robust training loop is essential for model development. During each epoch, the loop performs the following steps:- Sets the model to training mode.
- Executes a forward pass and computes the loss.
- Performs a backward pass to calculate gradients.
- Updates the model parameters using the optimizer.
- Evaluates performance on the validation dataset.
- The model is set to training (
model.train()) and evaluation (model.eval()) modes appropriately. - Gradients are reset using
optimizer.zero_grad()at the beginning of each batch. - The validation phase is accelerated by disabling gradient computations with
torch.no_grad(). - Losses are accumulated and averaged per epoch to provide clear feedback during training.