Skip to main content
Congratulations on reaching this point! In this guide, we will explore how to build and train a machine learning model by constructing a simple neural network using PyTorch. We will cover the following topics:
  • 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
Let’s dive in!

Building a Simple Neural Network in PyTorch

In PyTorch, you can construct a neural network by defining a class that inherits from nn.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.
In this snippet, we create a random tensor and print its dimensions ([5, 10]), representing a batch of 5 samples with 10 features each.

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:
The transformation of features is as follows:
  • 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:
This example illustrates how data transitions from a batch of 5 samples with 10 features each to an output with a single predicted feature.

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:
This loop prints the names, sizes, and the first two values of each parameter, allowing you to verify that the network’s structure is as expected. Alternatively, you can print all parameters without their names:

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.
The learning rate and momentum settings help tune the training process efficiently.

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.
These dataloaders manage the batching of data and feed it to the model during both training and validation phases.

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.
To set up your device (CPU or GPU) and instantiate the model:
Next, define your loss function and optimizer as before:

Training and Validation Loop

Implementing a robust training loop is essential for model development. During each epoch, the loop performs the following steps:
  1. Sets the model to training mode.
  2. Executes a forward pass and computes the loss.
  3. Performs a backward pass to calculate gradients.
  4. Updates the model parameters using the optimizer.
  5. Evaluates performance on the validation dataset.
Here is an example training loop that runs for 3 epochs:
Key details to note:
  • 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.

Final Thoughts on Training

During the training process, monitoring both the training and validation losses is essential. If both decrease, the model is likely learning well. However, a significant disparity—where training loss decreases while validation loss remains stagnant or increases—might indicate overfitting. In this guide, we walked through constructing and analyzing a simple neural network and an image classification network, inspecting model parameters, setting up the necessary loss functions and optimizers, and implementing an effective training and validation loop. Happy coding and enjoy building your models! For more information on neural networks and model training, consider exploring the following resources:

Watch Video

Practice Lab