1. Home
  2. Explore
  3. Computer Science
  4. PyTorch Deep Learning

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

PyTorch Deep Learning

PyTorch for Deep Learning: Comprehensive Study Notes

Course Introduction and Philosophy

  • Course Goal: Teach the foundations of machine learning and deep learning using PyTorch, a leading deep learning framework.

  • Target Audience: Beginners with 3–6 months of Python experience who want to learn by writing code.

  • Core Philosophy: “If in doubt, run the code.” The course emphasizes hands-on practice over theory.

  • Key Resources:

    • Course materials on GitHub (mrdbourke/pytorch-deep-learning)

    • Free online book version at learnpytorch.io

    • Additional chapters (transfer learning, deployment, etc.) available through paid offerings at Zero to Mastery Academy

  • Learning Approach: Machine learning and deep learning are learned by building small projects and iterating rapidly.

Module 1: PyTorch Fundamentals

What is Machine Learning (and Deep Learning)?

Definition: Machine learning is the process of turning data (images, text, numbers, audio, etc.) into numbers and finding patterns in those numbers.

Traditional Programming vs. Machine Learning

  • Traditional: Inputs + Rules → Outputs. The programmer explicitly defines the rules.

  • Machine Learning (Supervised): Inputs + Desired Outputs → Rules. The algorithm learns the rules (patterns) from labeled examples.

Why Use ML/DL?

  • Complex problems: Tasks too difficult to program manually (e.g., self-driving cars, handwriting recognition).

  • Changing environments: Models can adapt to new data over time.

  • Large datasets: Discovering hidden insights in massive amounts of data.

When NOT to Use ML/DL (Google’s Rule #1)

  • If a simple, reliable rule-based system works (e.g., a few steps to reproduce a recipe), use that instead.

  • When explainability is required: Deep learning model internals (weights and biases) are not interpretable.

  • When errors are unacceptable: DL models are probabilistic, not deterministic.

  • When you have very little data: Deep learning typically requires large datasets.

Machine Learning vs. Deep Learning

  • Machine Learning (Shallow Algorithms)

    • Best for structured data (tables of numbers).

    • Common algorithms: Random Forest, Gradient Boosted Models (e.g., XGBoost), Support Vector Machines (SVM).

  • Deep Learning (Neural Networks)

    • Best for unstructured data (images, text, audio).

    • Common architectures: CNNs, RNNs, Transformers.

    • Built using PyTorch.

  • Key Insight: The problem determines which tool to use. The course focuses on deep learning but uses “ML” and “DL” somewhat interchangeably.

What are Neural Networks?

Process:

  1. Input data is numerically encoded into a tensor (a matrix of numbers).

  2. This tensor passes through a neural network.

  3. The network has an input layer, one or more hidden layers (which learn representations/patterns/features), and an output layer.

  4. Each hidden layer is a combination of linear (straight‑line) and nonlinear (non‑straight‑line) functions.

  5. The network outputs a learned representation (features/weights) that can be converted into a human‑understandable output (e.g., “cat” or “dog”).

Key terms: “learns representation”, “learns patterns in data”, “features”, and “weights” are all related concepts.

Learning Paradigms

  • Supervised Learning: Data has labels. The model learns to map input data to output labels.

  • Unsupervised/Self‑Supervised Learning: No labels. The model learns inherent structures from data on its own.

  • Transfer Learning: Takes patterns learned on one dataset and applies them to a new, different problem. This is a powerful technique used extensively in practice.

  • The course focuses on supervised learning and transfer learning.

What is PyTorch?

Definition: PyTorch is the most popular research deep learning framework. It allows writing fast deep learning code in Python, accelerated by GPUs.

Key Features:

  • Provides pre‑built models via torch.hub and torchvision.models.

  • Covers the full ML stack: data preprocessing, building models, and deployment.

  • Developed by Facebook/Meta, open‑sourced, and used by Tesla, Microsoft, and OpenAI.

Why a GPU? A GPU (Graphics Processing Unit) is extremely fast at the numerical calculations required for deep learning. PyTorch leverages GPUs through an interface called CUDA (for NVIDIA GPUs).

What is a Tensor?

Definition: The fundamental building block of data in PyTorch and deep learning. A tensor is a numerical representation of data. It can be a vector (1D), a matrix (2D), or have higher dimensions.

Workflow:

  1. Input data is encoded into a tensor.

  2. The tensor passes through a neural network, which performs mathematical operations on it.

  3. The network outputs another tensor.

  4. This output tensor is converted into a human‑understandable result.

PyTorch Core Workflow (The Steps)

  1. Data (preparing and loading): Get data into a numerical representation (tensors).

  2. Build/Pick a Model: Create a neural network architecture suitable for the problem.

    • Pick a loss function: Measures how wrong the model’s predictions are (lower is better).

    • Pick an optimizer: Adjusts the model’s parameters to improve the loss.

    • Build a training loop: The core learning algorithm.

  3. Fit the Model to Data: Training the model (the main learning step).

  4. Make Predictions (Inference): Use the trained model on new data.

  5. Evaluate the Model: Assess performance on unseen data.

  6. Improve through Experimentation: Tweak hyperparameters (layers, hidden units, learning rate, etc.).

  7. Save and Load the Model: Export the trained model for later use.


Module 2: PyTorch Workflow (Modeling a Linear Regression Problem)

This module demonstrates the core workflow with a simple linear regression task.

1. Data (Creating & Splitting)

  • A synthetic straight‑line dataset is created: y=0.7⋅X+0.3y = 0.7 \cdot X + 0.3y=0.7⋅X+0.3 (known weight 0.70.70.7, bias 0.30.30.3).

  • Data is split into training (80%) and test (20%) sets.

  • Visualization is key: A helper function plot_predictions() is defined to view the data.

2. Building a Model

  • Model Architecture: A LinearRegressionModel class subclasses torch.nn.Module.

  • Key Components:

    • __init__: Defines model parameters (weights and biases) as nn.Parameter() objects.

    • forward(): Defines the forward pass: y=weight⋅X+biasy = \text{weight} \cdot X + \text{bias}y=weight⋅X+bias.

  • The model is instantiated with random parameters.

  • Checking Contents: Use model.parameters() or model.state_dict() to see current weights and biases.

3. Picking a Loss Function and Optimizer

  • Loss Function: nn.L1Loss() (Mean Absolute Error – MAE). Used for regression (predicting a number).

    MAE=1n∑i=1n∣yi−y^i∣\text{MAE} = \frac{1}{n} \sum_{i=1}^{n} |y_i - \hat{y}_i|MAE=n1​∑i=1n​∣yi​−y^​i​∣
  • Optimizer: torch.optim.SGD() (Stochastic Gradient Descent). Updates model parameters.

  • Hyperparameter – Learning Rate (lr) controls the size of parameter updates. Common starting value: 0.01.

4. Building a Training Loop (Unofficial PyTorch Optimization Loop Song)

For each epoch:

  1. Forward Pass: y_pred = model(X_train) – data flows through the model.

  2. Calculate Loss: loss = loss_fn(y_pred, y_train) – measure how wrong the predictions are.

  3. Optimizer Zero Grad: optimizer.zero_grad() – reset gradients of model parameters.

  4. Backpropagation: loss.backward() – compute gradients of loss with respect to every parameter.

  5. Optimizer Step: optimizer.step() – update parameters to reduce the loss.

5. Building a Testing/Evaluation Loop

  • model.eval(): Puts the model in evaluation mode (turns off dropout, batch norm).

  • with torch.inference_mode(): Context manager that turns off gradient tracking for faster computation.

    • Forward pass: test_pred = model(X_test)

    • Calculate test loss: test_loss = loss_fn(test_pred, y_test)

6. Key Concepts & Common Errors (Top 3)

  1. Wrong Data Type (dtype): E.g., tensor is torch.long when torch.float32 is required.

  2. Wrong Shape: Mismatched tensor dimensions. Example: trying to multiply matrices of shape (3,2) and (3,2).

  3. Wrong Device: Tensor on CPU but model on GPU, or vice versa. Use .to(device) to move both to the same device.

7. Matrix Multiplication

  • Element‑wise multiplication: tensor * tensor

  • Matrix multiplication (dot product): torch.mm(tensor_a, tensor_b) or tensor_a @ tensor_b

    • Rule 1: Inner dimensions must match: e.g., (a, b) @ (b, c) works.

    • Rule 2: Resulting matrix has shape of outer dimensions: (a, c).

  • Common fix: If shapes don’t match, use transpose (.T) to swap axes.

8. Making Predictions and Evaluation

  • Inference mode: Always use with torch.inference_mode(): when making predictions to speed up code.

  • Improving the model: Training for more epochs is one form of experimentation. Other hyperparameters to adjust: learning rate, number of layers.

9. Saving and Loading a Model

  • Recommended approach: Save the model’s state_dict (a dictionary of learned parameters).

    • Save: torch.save(model.state_dict(), 'model.pth')

  • Loading:

    • Instantiate a new instance of the model class.

    • Load the saved state dict: new_model.load_state_dict(torch.load('model.pth'))

    • Move the new model to the correct device: new_model.to(device)


Module 3: Neural Network Classification with PyTorch

This module shifts from regression (predicting a number) to classification (predicting a category).

What is Classification?

  • Binary Classification: One thing or another (e.g., spam/not spam, cat/dog).

  • Multi‑class Classification: More than two categories, but only one label per sample (e.g., predict sushi, steak, or pizza).

  • Multi‑label Classification: Multiple labels can be assigned to one sample (e.g., an article tagged “deep learning” and “AI”).

Architecture of a Classification Neural Network

  • Input Layer: Shape matches number of features (pixels, attributes).

  • Hidden Layers: One or more layers with a nonlinear activation function (e.g., nn.ReLU()).

  • Output Layer: Shape matches number of classes.

  • Output Activation:

    • Binary Classification: torch.sigmoid() – outputs a probability between 0 and 1.

    • Multi‑class Classification: torch.softmax(dim=1) – outputs probabilities for each class that sum to 1.

  • Loss Functions:

    • Binary: nn.BCEWithLogitsLoss() (recommended, numerically stable).

    • Multi‑class: nn.CrossEntropyLoss().

The “Logits” Pipeline

  1. Logits: Raw, unnormalized outputs from the model’s final linear layer.

  2. Prediction Probabilities (Pred Probs): Apply an activation function:

    • Binary: y_pred_probs = torch.sigmoid(y_logits)

    • Multi‑class: y_pred_probs = torch.softmax(y_logits, dim=1)

  3. Prediction Labels (Pred Labels): Convert probabilities to concrete class labels:

    • Binary: y_pred_labels = torch.round(y_pred_probs) (threshold = 0.5)

    • Multi‑class: y_pred_labels = torch.argmax(y_pred_probs, dim=1) (index of highest probability)

The Missing Piece: Non‑linearity

  • A network with only linear layers can only find linear relationships (straight lines). It cannot solve problems like separating concentric circles.

  • Non‑linear activation functions are needed between linear layers to learn complex patterns.

  • nn.ReLU(): A common and effective non‑linear function. It sets all negative values to 0 and leaves positive values unchanged.

  • A neural network is therefore a stack of linear functions (e.g., nn.Linear) and non‑linear functions (e.g., nn.ReLU).


Module 4: Computer Vision with Convolutional Neural Networks (CNNs)

This module applies the classification workflow to image data using CNNs.

Computer Vision Libraries in PyTorch

  • torchvision: The main domain library for computer vision. Contains:

    • datasets: Pre‑built datasets (e.g., FashionMNIST, CIFAR‑10).

    • models: Pre‑trained model architectures.

    • transforms: Functions for manipulating image data (resizing, tensor conversion, data augmentation).

  • torch.utils.data.Dataset and torch.utils.data.DataLoader: Core PyTorch utilities for handling data in batches.

Getting a Vision Dataset: FashionMNIST

  • FashionMNIST: 28×28 grayscale images of 10 clothing items (e.g., T‑shirt, trouser, sneaker).

  • Split: 60,000 training images, 10,000 test images.

  • Image shape: [batch_size, color_channels, height, width]

    • Grayscale: color_channels = 1

    • Color (RGB): color_channels = 3

  • torchvision.datasets.FashionMNIST() downloads and prepares the data.

  • transform = transforms.ToTensor() converts PIL images or NumPy arrays into PyTorch tensors.

Data Loaders (Batching)

Why batching?

  1. Computational efficiency: Processing batches (rather than one sample at a time) is more efficient.

  2. More gradient updates per epoch: The model updates parameters once per batch, leading to faster learning.

  • DataLoader: An iterable that handles batching. Takes a Dataset and a batch_size (e.g., 32). Typically shuffles training data and provides batches of images and labels.

CNN Architecture (TinyVGG)

A CNN is particularly good at finding patterns in image data.

  • Key layer: nn.Conv2d – Learns features by sliding a small kernel (filter) across the image.

    • Hyperparameters: in_channels (input depth), out_channels (number of filters, i.e., hidden units), kernel_size (size of filter, e.g., 3×3), stride (how many pixels the kernel moves at each step), padding (adding extra pixels around the edge to preserve spatial size).

  • Key layer: nn.MaxPool2d – A non‑learnable layer that compresses the image by taking the maximum value from a small window (e.g., 2×2), reducing height and width.

Common architecture (TinyVGG):

  • Input: Image tensor (batch_size, channels, H, W)

  • Conv Block 1: Conv2d → ReLU → Conv2d → ReLU → MaxPool2d

  • Conv Block 2: Conv2d → ReLU → Conv2d → ReLU → MaxPool2d

  • Classifier: Flatten → Linear (maps the final feature map to the number of output classes)

Error Checklist for Custom Data

Always ensure your image data has the correct:

  1. Data type (float32)

  2. Shape (matches the model’s expected input)

  3. Device (on the same device as the model)

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent