Hello! Welcome to the next lesson in our module on Deep Learning with PyTorch.
In our previous session, we conceptually unpacked the engine of deep learning: forward propagation to make predictions and backpropagation to learn from errors. We saw how PyTorch abstracts away the complex calculus of backpropagation with its autograd engine and the standard five-step training loop.
Today, we'll move from that conceptual blueprint to a concrete implementation. This lesson is all about fulfilling the learning outcome: Build a neural network model for a classification task using PyTorch. We'll translate an architectural design into a working Python class that you can instantiate, inspect, and use. Given your background as a software engineer, you'll find PyTorch's object-oriented approach to model building very intuitive.
1. The Anatomy of a PyTorch Model
In PyTorch, a neural network is defined as a Python class that inherits from a base class called torch.nn.Module. This structure provides a standardized way to manage the network's components (layers, weights, etc.) and its functionality.
Every model class you build will have two essential methods:
__init__(self): The constructor. This is where you define and initialize the building blocks of your network—the layers. These could be linear layers, activation functions, or other specialized modules.forward(self, x): This method defines the "forward pass." It dictates how input dataxflows through the layers you defined in__init__. The output of this method is the model's prediction.
Let's start by examining a complete, well-structured example from the official PyTorch documentation.
The official PyTorch documentation provides the best starting point for understanding how to structure a model. This tutorial introduces the core concepts and shows a clear, practical example for a multi-class classification problem (classifying images of clothing).
Please read from the beginning down to and including the 'Define the Class' section. Focus on how the NeuralNetwork class is structured: it inherits from nn.Module, layers are defined in __init__, and the forward method specifies how the input x flows through these layers. Also, note the use of nn.Sequential, a convenient container for chaining layers together in order.
As you saw in the reading, the NeuralNetwork class is a self-contained unit. Instantiating it (model = NeuralNetwork()) creates an object that holds both the network's structure and its parameters (weights and biases).
2. A Closer Look at the Building Blocks
The model in the tutorial was built using several standard layer types from the torch.nn library. Let's briefly break down the key ones. This will help you understand what each line in the __init__ method accomplishes.
nn.Linear(in_features, out_features): This is a fully connected layer. It applies a linear transformation . It takes the number of input features and output features as arguments. This is the workhorse layer that contains the learnable weights (A) and biases (b).nn.ReLU(): The Rectified Linear Unit activation function. As we discussed, it introduces non-linearity by returningmax(0, x), effectively turning off neurons that have negative outputs.nn.Flatten(): A utility layer that reshapes a multi-dimensional tensor into a one-dimensional vector. In the example, it converts the 2D image tensor (28x28) into a 1D vector of 784 pixels before feeding it to the first linear layer.nn.Softmax(dim=1): This activation function is crucial for multi-class classification. It converts a vector of raw output scores (logits) into a probability distribution, where each element is between 0 and 1, and all elements sum to 1. Thedim=1argument specifies that the softmax operation should be applied across the feature dimension for each sample in a batch.
The following image provides an excellent visual bridge between a network diagram and the corresponding PyTorch code, reinforcing how these components fit together.

3. Adapting the Model for Binary Classification
The previous example was for multi-class classification (10 classes in FashionMNIST). What if our task is binary classification (e.g., spam or not spam, cat or dog)? The architecture is very similar, but with two key changes in the output layer:
- The final
nn.Linearlayer will haveout_features=1. - The final activation function will be
nn.Sigmoid(), which squashes the single output value to a number between 0 and 1. This value can be interpreted as the probability of the "positive" class.
Let's look at a practical example.
Building a Binary Classification Model in PyTorch
Now let's see how to build a model specifically for a binary classification task. This resource demonstrates this by defining a model to classify sonar signals.
Please read the section 'Creating a Model' and focus on the code for the Wide class. Observe the two key differences for binary classification: the output layer is defined as nn.Linear(180, 1), and the final activation is self.sigmoid = nn.Sigmoid().
To summarize the differences:
| Feature | Binary Classification (Wide model) |
Multi-Class Classification (NeuralNetwork model) |
|---|---|---|
| Output Layer | nn.Linear(..., 1) |
nn.Linear(..., num_classes) |
| Final Activation | nn.Sigmoid() |
nn.Softmax(dim=1)* |
| Output Shape | A single value (probability) | A vector of num_classes values (probabilities) |
*A quick but important note: In practice, when using PyTorch's nn.CrossEntropyLoss for multi-class classification (which we will cover in the next lesson), you should not include a Softmax layer in your model. The loss function is optimized to take the raw logits directly. We include Softmax here to illustrate how you would get probabilities from the model itself.
Test your understanding!
You are given a tabular dataset for predicting customer churn. Each customer is represented by a vector of 30 features. Your goal is to build a binary classifier (churn vs. not churn).
Define a PyTorch model class called ChurnPredictor. It should have one hidden layer with 64 neurons and a ReLU activation function. Make sure the input and output dimensions are correct for this task.
Show answer
Here is a possible implementation. The key aspects are the input dimension of the first linear layer (30), the output dimension of the hidden layer (64), the final output dimension (1), and the use of nn.Sigmoid.
import torch
import torch.nn as nn
class ChurnPredictor(nn.Module):
def __init__(self):
super().__init__()
self.layer1 = nn.Linear(30, 64)
self.relu = nn.ReLU()
self.output_layer = nn.Linear(64, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = self.relu(self.layer1(x))
x = self.sigmoid(self.output_layer(x))
return x
# You can instantiate and test it with a dummy input
model = ChurnPredictor()
dummy_input = torch.randn(1, 30) # A single sample with 30 features
prediction = model(dummy_input)
print(f"Model: {model}")
print(f"Prediction for dummy input: {prediction.item()}")
Conclusion
In this lesson, we took the crucial step of turning an abstract network design into a concrete and functional PyTorch nn.Module. You now have the skills to construct your own neural network architectures for both binary and multi-class classification tasks.
Key Takeaways:
- Model as a Class: PyTorch models are classes that inherit from
nn.Module, with layers defined in__init__and the data flow defined inforward. This object-oriented design makes models modular and reusable. - Layer Composition: You build complex networks by composing basic layers like
nn.Linear,nn.ReLU,nn.Flatten, andnn.Sequential. - Task-Specific Outputs: The architecture of the output layer is determined by the task. For binary classification, use a single output neuron with a
Sigmoidactivation. For multi-class, usenum_classesoutput neurons, typically followed bySoftmax(or fed directly intoCrossEntropyLoss).
Next up:
We have now built our model's "body." In the next lesson, we will give it a "brain" by implementing the complete training loop. We'll bring together the model you learned to build today, a loss function to measure error, and an optimizer to update the model's weights, training it end-to-end on a dataset.