Learn the Basics || Quickstart || Tensors || Datasets & DataLoaders || Transforms || Build Model || Autograd || Optimization || Save & Load Model

Build the Neural Network

Neural networks comprise of layers/modules that perform operations on data. The torch.nn namespace provides all the building blocks you need to build your own neural network. Every module in PyTorch subclasses the nn.Module. A neural network is a module itself that consists of other modules (layers). This nested structure allows for building and managing complex architectures easily.

In the following sections, we’ll build a neural network to classify images in the FashionMNIST dataset.

import os
import torch
from torch import nn
from import DataLoader
from torchvision import datasets, transforms

Get Device for Training

We want to be able to train our model on a hardware accelerator like the GPU, if it is available. Let’s check to see if torch.cuda is available, else we continue to use the CPU.

device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(f'Using {device} device')


Using cuda device

Define the Class

We define our neural network by subclassing nn.Module, and initialize the neural network layers in __init__. Every nn.Module subclass implements the operations on input data in the forward method.

class NeuralNetwork(nn.Module):
    def __init__(self):
        super(NeuralNetwork, self).__init__()
        self.flatten = nn.Flatten()
        self.linear_relu_stack = nn.Sequential(
            nn.Linear(28*28, 512),
            nn.Linear(512, 512),
            nn.Linear(512, 10),

    def forward(self, x):
        x = self.flatten(x)
        logits = self.linear_relu_stack(x)
        return logits

We create an instance of NeuralNetwork, and move it to the device, and print its structure.

model = NeuralNetwork().to(device)


  (flatten): Flatten(start_dim=1, end_dim=-1)
  (linear_relu_stack): Sequential(
    (0): Linear(in_features=784, out_features=512, bias=True)
    (1): ReLU()
    (2): Linear(in_features=512, out_features=512, bias=True)
    (3): ReLU()
    (4): Linear(in_features=512, out_features=10, bias=True)

To use the model, we pass it the input data. This executes the model’s forward, along with some background operations. Do not call model.forward() directly!

Calling the model on the input returns a 10-dimensional tensor with raw predicted values for each class. We get the prediction probabilities by passing it through an instance of the nn.Softmax module.

X = torch.rand(1, 28, 28, device=device)
logits = model(X)
pred_probab = nn.Softmax(dim=1)(logits)
y_pred = pred_probab.argmax(1)
print(f"Predicted class: {y_pred}")


Predicted class: tensor([3], device='cuda:0')

Model Layers

Let’s break down the layers in the FashionMNIST model. To illustrate it, we will take a sample minibatch of 3 images of size 28x28 and see what happens to it as we pass it through the network.

input_image = torch.rand(3,28,28)


torch.Size([3, 28, 28])


We initialize the nn.Flatten layer to convert each 2D 28x28 image into a contiguous array of 784 pixel values ( the minibatch dimension (at dim=0) is maintained).

flatten = nn.Flatten()
flat_image = flatten(input_image)


torch.Size([3, 784])


The linear layer is a module that applies a linear transformation on the input using its stored weights and biases.

layer1 = nn.Linear(in_features=28*28, out_features=20)
hidden1 = layer1(flat_image)


torch.Size([3, 20])


Non-linear activations are what create the complex mappings between the model’s inputs and outputs. They are applied after linear transformations to introduce nonlinearity, helping neural networks learn a wide variety of phenomena.

In this model, we use nn.ReLU between our linear layers, but there’s other activations to introduce non-linearity in your model.

print(f"Before ReLU: {hidden1}\n\n")
hidden1 = nn.ReLU()(hidden1)
print(f"After ReLU: {hidden1}")


Before ReLU: tensor([[-1.2026e-01,  8.3869e-01, -6.3199e-01, -2.3527e-02,  1.6532e-03,
         -2.8475e-01, -8.7484e-01, -1.2666e+00,  2.7670e-01,  8.0218e-02,
         -4.1686e-01, -3.4255e-01,  3.3431e-01, -4.8009e-02,  7.1416e-02,
         -2.5116e-01,  2.4857e-01,  1.9477e-01,  4.7467e-01,  3.5611e-01],
        [ 2.5624e-01,  7.7880e-01, -5.3417e-01, -1.3101e-01, -4.5762e-03,
         -5.5660e-01, -6.7892e-01, -7.2230e-01,  1.5180e-01,  1.0480e-02,
         -4.9452e-01, -1.6586e-01, -5.0184e-02, -4.2672e-01,  5.7865e-02,
         -4.4630e-01,  4.9483e-01,  4.1107e-01,  5.9240e-01,  9.2006e-02],
        [-1.9568e-02,  7.8901e-01, -6.0017e-01, -2.3766e-01, -8.6511e-02,
         -2.1294e-01, -8.9644e-01, -8.2486e-01,  1.0437e-01, -1.3163e-01,
         -3.9008e-01, -6.1834e-01, -1.5039e-02, -2.9008e-01, -1.0883e-01,
         -4.5930e-01,  7.0497e-01, -7.6821e-02,  8.3154e-01, -3.9852e-04]],

After ReLU: tensor([[0.0000, 0.8387, 0.0000, 0.0000, 0.0017, 0.0000, 0.0000, 0.0000, 0.2767,
         0.0802, 0.0000, 0.0000, 0.3343, 0.0000, 0.0714, 0.0000, 0.2486, 0.1948,
         0.4747, 0.3561],
        [0.2562, 0.7788, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.1518,
         0.0105, 0.0000, 0.0000, 0.0000, 0.0000, 0.0579, 0.0000, 0.4948, 0.4111,
         0.5924, 0.0920],
        [0.0000, 0.7890, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.1044,
         0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.7050, 0.0000,
         0.8315, 0.0000]], grad_fn=<ReluBackward0>)


nn.Sequential is an ordered container of modules. The data is passed through all the modules in the same order as defined. You can use sequential containers to put together a quick network like seq_modules.

seq_modules = nn.Sequential(
    nn.Linear(20, 10)
input_image = torch.rand(3,28,28)
logits = seq_modules(input_image)


The last linear layer of the neural network returns logits - raw values in [-infty, infty] - which are passed to the nn.Softmax module. The logits are scaled to values [0, 1] representing the model’s predicted probabilities for each class. dim parameter indicates the dimension along which the values must sum to 1.

softmax = nn.Softmax(dim=1)
pred_probab = softmax(logits)

Model Parameters

Many layers inside a neural network are parameterized, i.e. have associated weights and biases that are optimized during training. Subclassing nn.Module automatically tracks all fields defined inside your model object, and makes all parameters accessible using your model’s parameters() or named_parameters() methods.

In this example, we iterate over each parameter, and print its size and a preview of its values.

print("Model structure: ", model, "\n\n")

for name, param in model.named_parameters():
    print(f"Layer: {name} | Size: {param.size()} | Values : {param[:2]} \n")


Model structure:  NeuralNetwork(
  (flatten): Flatten(start_dim=1, end_dim=-1)
  (linear_relu_stack): Sequential(
    (0): Linear(in_features=784, out_features=512, bias=True)
    (1): ReLU()
    (2): Linear(in_features=512, out_features=512, bias=True)
    (3): ReLU()
    (4): Linear(in_features=512, out_features=10, bias=True)

Layer: linear_relu_stack.0.weight | Size: torch.Size([512, 784]) | Values : tensor([[ 0.0289, -0.0129,  0.0086,  ..., -0.0317, -0.0012, -0.0331],
        [-0.0048, -0.0146,  0.0163,  ...,  0.0347, -0.0214,  0.0258]],
       device='cuda:0', grad_fn=<SliceBackward0>)

Layer: linear_relu_stack.0.bias | Size: torch.Size([512]) | Values : tensor([0.0001, 0.0229], device='cuda:0', grad_fn=<SliceBackward0>)

Layer: linear_relu_stack.2.weight | Size: torch.Size([512, 512]) | Values : tensor([[-0.0094,  0.0144,  0.0412,  ...,  0.0039,  0.0249,  0.0256],
        [ 0.0018,  0.0119,  0.0303,  ...,  0.0271,  0.0083,  0.0059]],
       device='cuda:0', grad_fn=<SliceBackward0>)

Layer: linear_relu_stack.2.bias | Size: torch.Size([512]) | Values : tensor([ 0.0383, -0.0189], device='cuda:0', grad_fn=<SliceBackward0>)

Layer: linear_relu_stack.4.weight | Size: torch.Size([10, 512]) | Values : tensor([[-0.0044,  0.0169, -0.0405,  ...,  0.0305, -0.0122,  0.0041],
        [ 0.0134,  0.0092,  0.0063,  ..., -0.0264,  0.0013,  0.0336]],
       device='cuda:0', grad_fn=<SliceBackward0>)

Layer: linear_relu_stack.4.bias | Size: torch.Size([10]) | Values : tensor([5.3368e-03, 4.2663e-05], device='cuda:0', grad_fn=<SliceBackward0>)


Access comprehensive developer documentation for PyTorch

View Docs


Get in-depth tutorials for beginners and advanced developers

View Tutorials


Find development resources and get your questions answered

View Resources