Neural Networks • Neural Network Foundations • 14 min read

Deep Learning with PyTorch

Start with an example: What actually happens when a model learns?

Suppose you want to predict whether a flower belongs to one of two species using four numerical measurements. You could write rules yourself, or you could give examples to a neural network and let it adjust its weights.

In PyTorch, a training iteration usually follows a repeatable sequence: convert examples into tensors, run the model to get predictions, calculate a loss that measures the prediction error, use automatic differentiation to calculate gradients, and ask an optimizer to update the weights. The next iteration starts with the updated weights.

This is useful because you can inspect every step. PyTorch does not make a bad dataset good, and a falling training loss does not prove the model will work on unseen examples. Keeping a separate test set and choosing a task-appropriate metric remain your responsibility.

PyTorch is an open-source framework for numerical computing and machine learning. It provides multidimensional arrays called tensors, operations that can run on CPUs or supported accelerators, automatic differentiation for computing gradients, and modules for constructing and training neural networks.

A useful way to learn PyTorch is to follow one model from its inputs to its predictions and then through training, evaluation, and deployment preparation. The framework handles many mathematical and computational details, but it does not choose an appropriate dataset, model, loss function, or evaluation strategy for you.

1. The components of a PyTorch project

ComponentPurposeTypical PyTorch API
TensorStore numerical data and learned parameterstorch.Tensor, torch.tensor
DatasetDefine how individual examples are accessedtorch.utils.data.Dataset
DataLoaderOrganize examples into batchestorch.utils.data.DataLoader
ModelDefine the transformations from input to outputtorch.nn.Module
LayersProvide reusable learnable operationstorch.nn.Linear, torch.nn.ReLU
Loss functionMeasure the discrepancy between outputs and targetstorch.nn.CrossEntropyLoss
AutogradCompute derivatives of tensor operationsloss.backward()
OptimizerUpdate parameters using gradientstorch.optim.Adam, torch.optim.SGD
Evaluation modeControl the behavior of certain layersmodel.eval()
CheckpointPreserve model parameters for later usestate_dict(), torch.save()
PyTorch training loop: batch of inputs and targets, model, loss, backward gradient computation, and optimizer parameter update
The training cycle connects a forward computation, a loss, gradients, and a parameter update. Labels are used by the loss function, not as model inputs.

2. Tensors, shapes, and data types

A tensor is a multidimensional collection of values. A scalar has zero axes, a vector has one, and a matrix has two. Larger tensors can represent batches of images, sequences, or other structured numerical data.

import torch

scalar = torch.tensor(3.0)
vector = torch.tensor([2.0, 4.0, 6.0])
matrix = torch.tensor([[1.0, 2.0], [3.0, 4.0]])

print(scalar.shape)  # torch.Size([])
print(vector.shape)  # torch.Size([3])
print(matrix.shape)  # torch.Size([2, 2])
print(matrix.dtype)  # torch.float32

The shape indicates the length along each axis. Shape compatibility matters: a network expecting four input features cannot directly process an input with five features.

For a dense classifier, the most common conventions are:

  • Input features: [batch_size, num_features].
  • Model outputs, or logits: [batch_size, num_classes].
  • Integer class labels: [batch_size], with values from 0 to num_classes - 1.

PyTorch usually represents neural-network weights and inputs as floating-point tensors. For CrossEntropyLoss, class-index targets are integer tensors with dtype torch.long. Do not assume all data types are interchangeable.

Devices

A tensor resides on a device, typically the CPU or an available accelerator. Operations generally require their operands to be on compatible devices.

import torch

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
x = torch.randn(4, 3).to(device)
print(x.device)

This simple choice uses CUDA when available and otherwise falls back to CPU. Other supported backends, including Apple’s MPS, may be available on some installations. Accelerator availability depends on compatible hardware and how PyTorch was installed. For installation-specific commands, consult the official PyTorch installation instructions rather than assuming one command fits every computer.

3. Build a model with nn.Module

A module is a reusable model component. To define a network, subclass torch.nn.Module, construct its layers in __init__, and describe the forward computation in forward.

import torch
from torch import nn

class SmallClassifier(nn.Module):
    def __init__(self, input_features=2, hidden_features=16, classes=2):
        super().__init__()
        self.network = nn.Sequential(
            nn.Linear(input_features, hidden_features),
            nn.ReLU(),
            nn.Linear(hidden_features, classes),
        )

    def forward(self, x):
        return self.network(x)

model = SmallClassifier()
example = torch.randn(5, 2)
logits = model(example)
print(logits.shape)  # torch.Size([5, 2])

The first linear layer transforms two features into a 16-dimensional hidden representation. The ReLU activation introduces nonlinearity, allowing the network to learn more than a single linear decision boundary. The final layer produces two scores per example.

These scores are logits, not necessarily probabilities. nn.CrossEntropyLoss accepts logits directly and internally performs the log-softmax-related calculation needed for multiclass classification. Adding a softmax before that loss is unnecessary and can harm numerical stability.

Parameters and buffers

model.parameters() yields registered learnable parameters, such as weights and biases, for the optimizer. model.state_dict() holds the model’s registered parameter and persistent buffer state, such as running statistics in batch-normalization layers. Layers assigned as module attributes are registered automatically.

4. Automatic differentiation with autograd

During training, PyTorch records differentiable operations involving tensors that require gradients. Calling backward() on a scalar loss computes the gradients needed to update model parameters.

For a scalar parameter ww and loss L(w)L(w), the quantity of interest is

∂L∂w.\frac{\partial L}{\partial w}.

A small example makes the mechanism visible:

import torch

w = torch.tensor(2.0, requires_grad=True)
loss = (w - 5.0) ** 2
loss.backward()

print(w.grad.item())  # -6.0

Here L(w)=(w−5)2L(w)=(w-5)^2. Its derivative is 2(w−5)2(w-5), which is −6-6 when w=2w=2. Autograd computes that gradient from the recorded operations.

Important: PyTorch usually accumulates gradients in each parameter’s .grad field. A training loop should clear old gradients before computing new ones, commonly with optimizer.zero_grad().

5. Datasets, batching, and data leakage

A Dataset describes how to obtain examples and their corresponding targets. A DataLoader creates batches and can shuffle the training order. Mini-batches allow parameter updates without processing the full dataset at once.

Split data before fitting preprocessing transformations. For real datasets, estimate scaling parameters only from the training portion, then apply them unchanged to validation and test data. Fitting a scaler on all observations leaks information from held-out data into model development.

The following complete example uses synthetic data generated directly in PyTorch. Because its features are already on comparable scales, no feature scaling step is necessary.

6. Complete example: train a two-class classifier

The task is to predict whether the sum of two numerical features is positive. This is a deliberately simple, synthetic problem designed to make the training mechanics easy to inspect, not a benchmark for real-world model performance.

Run the following script with PyTorch installed. It creates separate training and test examples, constructs a network, trains it, evaluates it, and saves its weights.

import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

# Reproducible random-number generation for this demonstration.
torch.manual_seed(42)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Independent synthetic training and test sets.
x_train = torch.randn(1200, 2)
y_train = (x_train[:, 0] + x_train[:, 1] > 0).long()

x_test = torch.randn(300, 2)
y_test = (x_test[:, 0] + x_test[:, 1] > 0).long()

train_loader = DataLoader(
    TensorDataset(x_train, y_train),
    batch_size=64,
    shuffle=True,
)
test_loader = DataLoader(
    TensorDataset(x_test, y_test),
    batch_size=128,
    shuffle=False,
)

class Classifier(nn.Module):
    def __init__(self):
        super().__init__()
        self.layers = nn.Sequential(
            nn.Linear(2, 16),
            nn.ReLU(),
            nn.Linear(16, 2),
        )

    def forward(self, x):
        return self.layers(x)

model = Classifier().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)

# Training: compute predictions, loss, gradients, and updates.
for epoch in range(15):
    model.train()
    running_loss = 0.0
    total = 0

    for features, labels in train_loader:
        features = features.to(device)
        labels = labels.to(device)

        optimizer.zero_grad()
        logits = model(features)
        loss = criterion(logits, labels)
        loss.backward()
        optimizer.step()

        batch_size = labels.size(0)
        running_loss += loss.item() * batch_size
        total += batch_size

    print(f"Epoch {epoch + 1:02d}: training loss = {running_loss / total:.4f}")

# Evaluation: no gradient updates and no training-specific behavior.
model.eval()
correct = 0
seen = 0

with torch.inference_mode():
    for features, labels in test_loader:
        features = features.to(device)
        labels = labels.to(device)
        logits = model(features)
        predictions = logits.argmax(dim=1)
        correct += (predictions == labels).sum().item()
        seen += labels.size(0)

print(f"Test accuracy: {correct / seen:.2%}")

# Save model weights, not a serialized Python model object.
torch.save(model.state_dict(), "classifier-weights.pth")

Understand the training loop line by line

  1. model.train() enables training behavior for modules that distinguish training from evaluation, such as dropout and batch normalization.
  2. optimizer.zero_grad() clears gradients left from earlier updates.
  3. model(features) performs forward propagation and returns logits.
  4. criterion(logits, labels) computes the classification loss using the true labels.
  5. loss.backward() computes derivatives of the loss with respect to model parameters.
  6. optimizer.step() uses those gradients to update the parameters.
  7. The loop repeats for all batches and epochs.

The reported training loss is an example-weighted average across the epoch, rather than an unweighted mean of batch means. Weighting matters because the last batch may be smaller than the others.

Why evaluate on separate data?

A model can memorize training observations or learn dataset-specific patterns. The separate test set estimates how well it performs on new examples drawn from the same synthetic process. In a realistic project, use a validation set for model selection and hyperparameter tuning, reserving the test set for final evaluation.

Accuracy is easy to interpret for the balanced synthetic task. On imbalanced or high-stakes classification problems, also consider precision, recall, confusion matrices, probability calibration, and error costs.

7. Load the model and run inference

To reuse saved weights, create the same model architecture and load the state dictionary. Loading onto the CPU is a portable approach when a GPU is unavailable.

import torch

# This assumes the Classifier definition from the preceding example.
loaded_model = Classifier()
weights = torch.load(
    "classifier-weights.pth",
    map_location="cpu",
    weights_only=True,
)
loaded_model.load_state_dict(weights)
loaded_model.eval()

new_example = torch.tensor([[0.8, -0.2]], dtype=torch.float32)

with torch.inference_mode():
    logits = loaded_model(new_example)
    probabilities = torch.softmax(logits, dim=1)
    predicted_class = probabilities.argmax(dim=1).item()

print("Predicted class:", predicted_class)
print("Class probabilities:", probabilities.tolist())

model.eval() changes relevant module behavior; torch.inference_mode() disables autograd-related recording and can reduce inference overhead. They serve different purposes, so use both during ordinary inference.

weights_only=True is recommended for loading compatible weight checkpoints. Do not load untrusted serialized files casually: serialization formats and their loading mechanisms can present security risks.

8. Choose losses and output shapes correctly

The loss function must match the problem and the model’s outputs.

TaskTypical model outputCommon loss
Multiclass classificationOne logit per class: [batch, classes]nn.CrossEntropyLoss()
Binary classification with one logitOne logit per example: [batch, 1]nn.BCEWithLogitsLoss()
Numerical regressionContinuous prediction: [batch, targets]nn.MSELoss() or nn.L1Loss()

For two-class classification, either two logits with cross-entropy or one logit with binary cross-entropy can be used, but they require different target formats. BCEWithLogitsLoss expects floating-point binary targets of a compatible shape and incorporates the sigmoid operation internally.

A probability is not the same as a raw logit. Apply softmax for interpreting multiclass logits as probabilities during inference, not before CrossEntropyLoss. Apply sigmoid when converting a single binary logit to a probability for inference, not before BCEWithLogitsLoss.

9. Common errors and how to diagnose them

SymptomLikely issueFirst check
Shape mismatchIncorrect input width or target shapePrint features.shape, logits.shape, and labels.shape
Device mismatchData and model on different devicesCheck .device and move all tensors consistently
Dtype errorLabels or inputs use unsuitable typesInspect .dtype; cross-entropy class indices need torch.long
Training loss does not decreaseLearning rate, architecture, labels, or gradient update problemCheck optimizer steps and gradient values
Training looks good but test results are poorOverfitting or distribution mismatchCompare train/validation metrics and inspect leakage
Out-of-memory errorBatch or model is too largeReduce batch size or model size
Unstable evaluationTraining-mode layers remain activeCall model.eval() before inference

A good debugging strategy is to make the network overfit a tiny clean batch. If it cannot learn even a handful of examples, inspect the labels, loss, shapes, gradients, and optimizer before attempting a large-scale experiment. Overfitting a tiny batch is a diagnostic technique, not a valid final evaluation method.

10. From a tutorial to a reliable training project

A real project adds practices that the demonstration deliberately leaves out:

  • Data provenance: Document where examples came from, how labels were created, and whether collection and use are authorized.
  • Appropriate splits: Split by time, user, or group when independent random splitting would cause leakage.
  • Preprocessing: Fit transformations using training data only and save everything necessary to reproduce them.
  • Validation: Track held-out metrics during development; use early stopping or model selection without repeatedly consulting the test set.
  • Experiment tracking: Record the code version, configuration, random seeds, dataset version, and results.
  • Checkpoints: Save model and optimizer state when resuming training is required, not just inference weights.
  • Monitoring: Check accuracy, latency, failures, input distributions, and relevant operational constraints after deployment.
  • Security: Validate inputs and control access to models, checkpoints, datasets, and inference endpoints.

A fixed random seed improves reproducibility but does not guarantee identical results across every machine, accelerator, library version, or operation.

CPU and GPU considerations

PyTorch can execute many workloads on CPUs and supported accelerators. GPUs are especially useful for large tensor operations and neural networks, but small examples may run adequately on a CPU. Hardware acceleration does not automatically improve model quality; it mainly changes execution speed and available computational capacity.

Batch size trades off memory use, update frequency, and computational efficiency. Larger batches are not universally better. Monitor the model’s evaluation performance and actual training behavior rather than choosing batch size solely by GPU capacity.

11. How PyTorch relates to other AI tools

NumPy is useful for numerical arrays and conventional scientific computing. PyTorch tensors offer accelerator support and automatic differentiation for many numerical operations. Scikit-learn provides a broad collection of conventional machine-learning estimators and utilities. PyTorch is commonly selected when defining custom differentiable models and training neural networks, including CNNs, RNNs, and Transformers.

You do not need to reimplement automatic differentiation or every layer from scratch to understand their mathematics. You should, however, recognize what the abstractions compute and know how to test the assumptions behind them.

12. Practice exercises

  1. Change the hidden-layer width from 16 to 4 and then to 64. Compare training loss and test performance across several runs.
  2. Replace Adam with torch.optim.SGD and test several learning rates. Record which settings converge reliably.
  3. Add a validation set and choose the number of epochs without inspecting the final test labels.
  4. Adapt the example to single-logit binary classification using nn.BCEWithLogitsLoss; adjust the labels and output shape accordingly.
  5. Modify the saved-checkpoint workflow so training can resume with the optimizer state and current epoch number.

Prerequisites

Continue learning

Some continuation links lead to articles planned in the PlainCS knowledge map and will become active when those pages are published.

14. References and further reading

Related articles in

Image preview

Fit