Skip to main content
This note covers the core PyTorch concepts you need for machine learning and deep learning:
  1. What is PyTorch?
  2. Installation
  3. PyTorch workflow
  4. Tensors
  5. Tensor operations
  6. Dataset and DataLoader
  7. Transforms
  8. Neural networks
  9. Optimizers
  10. Autograd
  11. Backpropagation
  12. Loss functions
  13. Complete training loop
  14. Complete example

1. What is PyTorch?

PyTorch is an open-source deep learning framework developed by Meta AI. It is mainly used for:
  • Machine Learning
  • Deep Learning
  • Neural Networks
  • Computer Vision
  • Natural Language Processing
  • Generative AI
  • Reinforcement Learning
PyTorch provides:
  • Tensor computation
  • GPU acceleration
  • Automatic differentiation
  • Neural network building blocks
  • Optimizers
  • Dataset and DataLoader utilities

Simple idea


2. Install PyTorch

For a basic installation:
Check the installation:
Example output:

3. Import PyTorch

You will commonly use:

4. PyTorch Workflow

A typical PyTorch deep-learning project follows this workflow:

5. PyTorch Tensors

A tensor is the fundamental data structure in PyTorch. You can think of a tensor as a generalization of:
  • Scalar → 0D tensor
  • Vector → 1D tensor
  • Matrix → 2D tensor
  • Higher-dimensional array → 3D, 4D, etc.

5.1 Scalar

A scalar contains one value.
Output:

5.2 Vector

Output:

5.3 Matrix

Output:

6. Creating Tensors

torch.tensor()

Output:

torch.zeros()

Creates a tensor filled with zeros.
Output:

torch.ones()

Output:

torch.full()

Output:

torch.arange()

Output:

torch.linspace()

Creates evenly spaced values.
Output:

Random tensor

Example:
Values are between 0 and 1.

7. Tensor Data Types

Output:
Float tensor:
Output:
Convert datatype:
Output:

8. Tensor Shape

Output:
This means:

9. Tensor Indexing

Output:
For a matrix:
Output:

10. Tensor Slicing

Output:

11. Tensor Arithmetic

Output:

12. Matrix Multiplication

Matrix multiplication is extremely important in neural networks.
Output:
You can also use:

13. Reshaping Tensors

Use .reshape() to change the tensor shape.
Output:

14. Flatten

Flatten converts multiple dimensions into one dimension.
Output:
This is commonly used before fully connected layers.

15. Tensor Device — CPU and GPU

PyTorch can execute tensor operations on:
  • CPU
  • GPU
Check GPU availability:
Output might be:
Create device:
Move tensor to device:
Move model:
During training, both model and data must be on compatible devices.

16. Dataset

A Dataset represents your data. PyTorch provides:
A custom dataset normally implements:

17. Creating a Custom Dataset

Suppose we have:
Create the dataset:
Create dataset:
Output:
Get one sample:
Output:

18. Why Dataset?

Dataset provides a standard way to:
  • Store data
  • Access individual samples
  • Separate data from model logic
  • Work with DataLoader

19. DataLoader

A DataLoader loads data in batches.
Loop through batches:
Instead of processing:
all at once, DataLoader can process:

20. Important DataLoader Parameters

batch_size

Number of samples processed at once.
means:

shuffle

Randomizes the training data.
This helps prevent the model from learning based on the original ordering of training data.

21. Dataset vs DataLoader

Simple way to remember:

22. Transforms

Transforms are used to preprocess or modify data. Commonly used with:
  • Images
  • Computer vision
  • Data augmentation
Import:

23. ToTensor()

Converts image data into a PyTorch tensor.
Example:

24. Normalize

Normalization changes the scale of input data.
For RGB images:

25. Resize

Resize images to a fixed size.
This converts images to:

26. Data Augmentation

Data augmentation creates variations of training images. Example:
This can help reduce overfitting.

27. Compose

Compose combines multiple transformations.
Execution:

28. Neural Network in PyTorch

PyTorch provides:
Import:
A neural network usually inherits from:

29. Simple Neural Network

Create model:
Output:

30. Understanding nn.Linear

means:
Mathematically:
where:
  • x = input
  • W = weights
  • b = bias
  • y = output

31. Multiple Layers

Architecture:

32. Activation Function

Activation functions introduce non-linearity. Common activations:
Example:
Output:

33. Loss Function

Loss measures how wrong the model’s prediction is. Concept:
Common loss functions:

34. MSE Loss

Mean Squared Error is commonly used for regression.
Example:
Output:
Because:

35. Optimizers

An optimizer updates the model’s parameters to reduce the loss. Common optimizers:
  • SGD
  • Adam
  • RMSprop
  • AdamW

36. SGD Optimizer

SGD = Stochastic Gradient Descent.
Here:
The optimizer uses gradients to update weights. Conceptually:

37. Adam Optimizer

Adam is one of the most commonly used optimizers.
Adam adapts the update for each parameter using information from past gradients. A common starting point is:

38. Optimizer Comparison


39. What is Autograd?

Autograd is PyTorch’s automatic differentiation system. It automatically calculates gradients. Example:
Output:
Why? We have:
Derivative:
At:
therefore:
PyTorch calculates this automatically.

40. requires_grad=True

When you write:
you tell PyTorch:
Track operations involving this tensor because I may need its gradient.
Check:
Output:

41. Gradient

A gradient tells us how much a value changes when a parameter changes. Example:
Output:
Because:

42. .backward()

The .backward() function calculates gradients. Example:
Mathematically:
Output:

43. Computational Graph

PyTorch creates a computational graph when operations are performed on tensors that require gradients. Example:
Graph:
When you call:
PyTorch calculates gradients through this graph.

44. Backpropagation

Backpropagation is the process of calculating how much each model parameter contributed to the error. Basic flow:

45. Forward Pass

Suppose:
The neuron calculates:
Therefore:
In PyTorch:

46. Complete Autograd Example

Let’s understand it.

Forward calculation

Target:
Loss:
Then:
calculates:

47. Gradient Descent Manually

Suppose:
Update:
Therefore:
PyTorch’s optimizer performs this update automatically.

48. The Three Important Optimizer Steps

During training, you commonly see:
then:
then:
These are extremely important.

Step 1 — zero_grad()

Clears previously stored gradients. PyTorch accumulates gradients by default.

Step 2 — backward()

Calculates gradients.

Step 3 — step()

Updates model parameters using those gradients.

49. Complete Training Loop

This is the core PyTorch training pattern.

50. Complete Regression Example

Let’s build a simple model that learns:
Dataset:

Step 1 — Import libraries


Step 2 — Create data


Step 3 — Create Dataset

TensorDataset is convenient when your data is already stored as tensors.

Step 4 — Create DataLoader


Step 5 — Create Model

The model contains:

Step 6 — Loss Function


Step 7 — Optimizer


Step 8 — Training


51. Make a Prediction

After training:
Expected result:
Because the model learned approximately:
For:
we expect:

52. Complete PyTorch Example

Here is the same example in one place:
Expected:

53. Training Loop Explained

The most important part is:
This is the forward pass. Then:
This calculates the error. Then:
Clears previous gradients. Then:
Calculates gradients using backpropagation. Finally:
Updates weights. So remember:

54. Why Do We Need zero_grad()?

Consider:
PyTorch accumulates gradients. For example:
Usually we want each training iteration to use its own gradients. Therefore:
is used before:

55. model.train()

During training:
Example:
This puts the model into training mode. It matters especially for layers such as:
  • Dropout
  • Batch Normalization

56. model.eval()

During evaluation:
Example:

57. torch.no_grad()

During prediction, gradients usually aren’t required. Use:
Advantages:
  • Less memory usage
  • Faster inference
  • No unnecessary gradient calculations

58. Training vs Evaluation

Training

Evaluation


59. Classification Example

For a multi-class classification problem:
Suppose:
The output is:
Use:

60. Classification Training

Training:

61. Important PyTorch Concepts


62. Epoch vs Batch vs Iteration

Suppose:
Then:
Number of batches:
Therefore:

63. Learning Rate

Learning rate controls how much the model changes its weights. Example:
Small learning rate:
May train slowly. Large learning rate:
May overshoot the optimal solution. Typical values depend on the optimizer and model.

64. Model Parameters

A neural network contains learnable parameters. Example:
It has:
Inspect them:

65. Saving a Model

Save model parameters:
Load them:
state_dict() contains the model’s learned parameters.

66. Complete Conceptual Picture

The complete process can be visualized as:

67. Most Important Code to Remember

If you’re learning PyTorch for interviews or practical ML, remember this pattern:
The four lines you should especially remember are:

68. PyTorch Cheat Sheet

Import

Tensor

Random Tensor

Shape

Reshape

Device

Dataset

DataLoader

Neural Network

Linear Layer

ReLU

Loss

Classification Loss

Optimizer

Gradient

Update

Clear Gradient

Training Mode

Evaluation Mode

Disable Gradients


69. The Big Picture

The concepts you asked about are connected: