Learn PyTorch · 3/12

Building Neural Networks with torch.nn

7 min read

Building Neural Networks with torch.nn 🧠

Welcome back! So far, we've been wrangling tensors, which is fun, but now it's time to build the real machinery of deep learning: neural networks. The torch.nn package is your go-to toolkit for this. It provides all the building blocks you need, so you don't have to build everything from scratch. Think of it as a super-fancy LEGO set for creating intelligent systems.


1. The nn.Module Base Class: Structure and the forward Method

At the heart of every PyTorch model is the nn.Module class. Every neural network you build will be a subclass of nn.Module. This nested structure allows for building and managing complex architectures easily.

Imagine you're designing a new kind of robot. You'd first create a blueprint (nn.Module) that outlines its different parts and how they connect.

The Core Idea

  • Definition: nn.Module is the base class for all neural network modules in PyTorch. Your own models will inherit from this class.
  • Problem: When building a neural network, you need a way to organize its layers, manage its parameters (like weights and biases), and define how data flows through it.
  • Solution: nn.Module provides a structured way to do all of this. It keeps track of all the layers and their learnable parameters.

The __init__ and forward Methods

When you create your own neural network class, you'll primarily be working with two special methods:

  • __init__(): This is where you define the layers of your network. You'll create instances of layers like linear layers, convolutional layers, etc., and assign them as attributes of your class.
  • forward(): This method defines the "forward pass" of your network. It specifies how the input data travels through the layers you defined in __init__() to produce an output.

Let's see this in action with a simple example:

python
import torch
import torch.nn as nn

class SimpleNet(nn.Module):
    def __init__(self):
        super(SimpleNet, self).__init__()
        # Define the layers
        self.fc1 = nn.Linear(784, 128)  # Fully connected layer
        self.relu = nn.ReLU()           # Activation function
        self.fc2 = nn.Linear(128, 10)   # Output layer

    def forward(self, x):
        # Define the data flow
        x = self.fc1(x)
        x = self.relu(x)
        x = self.fc2(x)
        return x

# Create an instance of our network
model = SimpleNet()
print(model)

In this example, SimpleNet inherits from nn.Module. In the __init__ method, we define two linear layers and a ReLU activation. The forward method then dictates that an input x will first pass through fc1, then the relu activation, and finally fc2.

🧠 Fun Fact: The forward method is what gets called when you pass input to your model instance, like model(input_data). This is thanks to a special __call__ method in the nn.Module class.


2. Standard Layers: Linear, Activation Functions, and Dropout

Now, let's look at some of the most common "LEGO bricks" you'll use from torch.nn.

nn.Linear: The Workhorse Layer

  • Definition: A linear layer applies a linear transformation to the incoming data: y = xA^T + b.
  • Problem: How do you connect neurons between different layers? You need a way to apply weights and biases to the inputs.
  • Solution: The nn.Linear layer does exactly this. It's your standard, fully-connected neural network layer.

When you create an nn.Linear layer, you need to specify the in_features (the number of input neurons) and out_features (the number of output neurons).

python
# A linear layer that takes 784 inputs and produces 128 outputs
linear_layer = nn.Linear(784, 128)

Activation Functions: Adding Non-Linearity

  • Definition: Activation functions introduce non-linearities into the network, allowing it to learn more complex patterns.
  • Problem: If you just stack linear layers, no matter how many you have, the entire network is still just a single linear transformation. This limits the model's ability to learn from complex, non-linear data.
  • Solution: Activation functions are applied after linear transformations to introduce non-linearity.

Here are a couple of popular ones:

  • nn.ReLU() (Rectified Linear Unit): It's the most commonly used activation function in modern deep learning. It's simple: it returns the input if it's positive, and zero otherwise.
    • Pros: Computationally efficient and helps with the vanishing gradient problem.
  • nn.Sigmoid(): This function squashes the input values to be between 0 and 1.
    • Use Case: Often used in the output layer for binary classification tasks where the output represents a probability.

nn.Dropout: Preventing Overfitting

  • Definition: Dropout is a regularization technique that randomly sets a fraction of input units to 0 at each update during training time to prevent overfitting.
  • Problem: When a neural network is trained on a dataset for too long, it can start to memorize the training data, including its noise. This is called overfitting, and it leads to poor performance on new, unseen data.
  • Solution: During training, a dropout layer will randomly "drop" a certain percentage of neurons. This forces the network to learn more robust features that are not overly reliant on any single neuron.
python
# A dropout layer with a 50% probability of dropping out neurons
dropout_layer = nn.Dropout(p=0.5)

Important Note: Dropout is only active during training. During evaluation or inference, it acts as an identity function, meaning it doesn't drop any neurons.


3. Using nn.Sequential for Rapid Prototyping

  • Definition: nn.Sequential is a container that allows you to build a neural network by passing a sequence of layers.
  • Problem: For simpler models where the data flows through the layers in a straightforward, linear fashion, writing a full class with __init__ and forward can be a bit verbose.
  • Solution: nn.Sequential provides a more concise way to create such models.

Here's how you can build the same SimpleNet from before using nn.Sequential:

python
import torch
import torch.nn as nn

model_sequential = nn.Sequential(
    nn.Linear(784, 128),
    nn.ReLU(),
    nn.Linear(128, 10)
)

print(model_sequential)

This code creates the exact same network architecture as our SimpleNet class, but in a much more compact way.

Industry Practice: While nn.Sequential is great for simple, linear stacks of layers, for more complex models with multiple inputs/outputs or skip connections, you'll want to subclass nn.Module for maximum flexibility.


4. Inspecting Model Parameters and States

Once you've built your model, you'll often need to inspect its parameters (weights and biases) and its state.

Accessing Parameters

You can access all the learnable parameters of a model using the .parameters() method.

python
for param in model.parameters():
    print(param.shape)

For more detailed information, you can use .named_parameters() which returns both the name of the parameter and the parameter itself.

python
for name, param in model.named_parameters():
    print(f"Layer: {name}, Shape: {param.shape}")

The state_dict

  • Definition: A state_dict is a Python dictionary object that maps each layer to its parameter tensor.
  • Problem: How do you save and load your trained model? You need a way to store all the learned weights and biases.
  • Solution: The state_dict is the recommended way to save and load model parameters. It gives you more flexibility because it only saves the model's parameters, not the entire model structure.

Here's how you can get the state_dict and save it:

python
# Get the state_dict
model_state = model.state_dict()
print(model_state.keys())

# Save the state_dict
torch.save(model_state, 'model_state.pth')

And here's how you would load it back into a model instance:

python
# Create a new instance of the model
new_model = SimpleNet()

# Load the saved state_dict
new_model.load_state_dict(torch.load('model_state.pth'))
new_model.eval() # Set the model to evaluation mode

Real-world Scenario: Imagine you've spent days training a massive model. Saving the state_dict allows you to create a checkpoint. If your training gets interrupted, you can simply load the last saved state_dict and continue from where you left off, saving you a lot of time and computational resources.


Additional Resources for Extra Reading 📚

Challenge

Task

You are tasked with building a neural network for a binary classification problem. Create a Python class named AdvancedClassifier that inherits from torch.nn.Module.

Requirements:

  1. __init__ method:

    • Call the constructor of the parent class (nn.Module).
    • Initialize the following layers in order as instance attributes:
      1. A fully connected layer that takes 512 input features and produces 256 output features.
      2. A ReLU activation function.
      3. A dropout layer with a dropout probability of 0.5.
      4. A second fully connected layer that maps 256 features to 128.
      5. A second ReLU activation function.
      6. A final fully connected layer that maps 128 features to a single output feature.
      7. A Sigmoid activation function to constrain the output for classification.
  2. forward method:

    • Define the forward pass of the network.
    • The method should accept one argument, an input tensor x.
    • It must pass the input tensor sequentially through all the layers defined in the __init__ method in the correct order.
    • Return the final output tensor.

Expected result

Your code should define a class AdvancedClassifier inheriting from nn.Module. The class must have a correct __init__ method that defines all the required layers and a forward method that correctly implements the data flow through those layers.

Here is an example of a valid solution:

python
import torch
import torch.nn as nn

class AdvancedClassifier(nn.Module):
    def __init__(self):
        super(AdvancedClassifier, self).__init__()
        self.fc1 = nn.Linear(512, 256)
        self.relu1 = nn.ReLU()
        self.dropout = nn.Dropout(p=0.5)
        self.fc2 = nn.Linear(256, 128)
        self.relu2 = nn.ReLU()
        self.fc3 = nn.Linear(128, 1)
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        x = self.fc1(x)
        x = self.relu1(x)
        x = self.dropout(x)
        x = self.fc2(x)
        x = self.relu2(x)
        x = self.fc3(x)
        x = self.sigmoid(x)
        return x
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.