- What is PyTorch?
- Installation
- PyTorch workflow
- Tensors
- Tensor operations
- Dataset and DataLoader
- Transforms
- Neural networks
- Optimizers
- Autograd
- Backpropagation
- Loss functions
- Complete training loop
- 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
- Tensor computation
- GPU acceleration
- Automatic differentiation
- Neural network building blocks
- Optimizers
- Dataset and DataLoader utilities
Simple idea
2. Install PyTorch
For a basic installation:3. Import PyTorch
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.5.2 Vector
5.3 Matrix
6. Creating Tensors
torch.tensor()
torch.zeros()
Creates a tensor filled with zeros.
torch.ones()
torch.full()
torch.arange()
torch.linspace()
Creates evenly spaced values.
Random tensor
0 and 1.
7. Tensor Data Types
8. Tensor Shape
9. Tensor Indexing
10. Tensor Slicing
11. Tensor Arithmetic
12. Matrix Multiplication
Matrix multiplication is extremely important in neural networks.13. Reshaping Tensors
Use.reshape() to change the tensor shape.
14. Flatten
Flatten converts multiple dimensions into one dimension.15. Tensor Device — CPU and GPU
PyTorch can execute tensor operations on:- CPU
- GPU
16. Dataset
A Dataset represents your data. PyTorch provides:17. Creating a Custom Dataset
Suppose we have:18. Why Dataset?
Dataset provides a standard way to:- Store data
- Access individual samples
- Separate data from model logic
- Work with DataLoader
19. DataLoader
ADataLoader loads data in batches.
20. Important DataLoader Parameters
batch_size
Number of samples processed at once.
shuffle
Randomizes the 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
23. ToTensor()
Converts image data into a PyTorch tensor.
24. Normalize
Normalization changes the scale of input data.25. Resize
Resize images to a fixed size.26. Data Augmentation
Data augmentation creates variations of training images. Example:27. Compose
Compose combines multiple transformations.
28. Neural Network in PyTorch
PyTorch provides:29. Simple Neural Network
30. Understanding nn.Linear
x= inputW= weightsb= biasy= output
31. Multiple Layers
32. Activation Function
Activation functions introduce non-linearity. Common activations:33. Loss Function
Loss measures how wrong the model’s prediction is. Concept:34. MSE Loss
Mean Squared Error is commonly used for regression.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.37. Adam Optimizer
Adam is one of the most commonly used optimizers.38. Optimizer Comparison
39. What is Autograd?
Autograd is PyTorch’s automatic differentiation system. It automatically calculates gradients. Example:40. requires_grad=True
When you write:
Track operations involving this tensor because I may need its gradient.Check:
41. Gradient
A gradient tells us how much a value changes when a parameter changes. Example:42. .backward()
The .backward() function calculates gradients.
Example:
43. Computational Graph
PyTorch creates a computational graph when operations are performed on tensors that require gradients. Example:44. Backpropagation
Backpropagation is the process of calculating how much each model parameter contributed to the error. Basic flow:45. Forward Pass
Suppose:46. Complete Autograd Example
Forward calculation
47. Gradient Descent Manually
Suppose:48. The Three Important Optimizer Steps
During training, you commonly see:Step 1 — zero_grad()
Step 2 — backward()
Step 3 — step()
49. Complete Training Loop
50. Complete Regression Example
Let’s build a simple model that learns: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
Step 6 — Loss Function
Step 7 — Optimizer
Step 8 — Training
51. Make a Prediction
After training:52. Complete PyTorch Example
Here is the same example in one place:53. Training Loop Explained
The most important part is:54. Why Do We Need zero_grad()?
Consider:
55. model.train()
During training:
- Dropout
- Batch Normalization
56. model.eval()
During evaluation:
57. torch.no_grad()
During prediction, gradients usually aren’t required.
Use:
- Less memory usage
- Faster inference
- No unnecessary gradient calculations
58. Training vs Evaluation
Training
Evaluation
59. Classification Example
For a multi-class classification problem:60. Classification Training
61. Important PyTorch Concepts
62. Epoch vs Batch vs Iteration
Suppose:63. Learning Rate
Learning rate controls how much the model changes its weights. Example:64. Model Parameters
A neural network contains learnable parameters. Example:65. Saving a Model
Save model parameters:state_dict() contains the model’s learned parameters.