MODULE 1.2: TENSOR OPERATIONS, INDEXING, SLICING & BROADCASTING MECHANICS

Master advanced tensor manipulation techniques in PyTorch. Learn how to index multi-dimensional data, slice memory efficiently, reshape tensor geometries, and apply automatic broadcasting rules using real-world e-commerce image batch processing examples.

💡 Foundational Overview

PyTorch is a popular software toolkit used to build and train Artificial Intelligence (AI) models. Its most important building block is the Tensor—a container that stores numbers in an organized way, like a spreadsheet that can have more than two dimensions. PyTorch can process tensor data quickly, especially with a GPU, and automatically calculate how a model should adjust itself while learning.

1. What Is PyTorch and Where Did It Come From?
Think of PyTorch as a toolbox for people who build AI applications. It provides ready-made tools for working with data, creating neural networks, training models, and testing predictions.
  • Who developed it? PyTorch was developed by a team at Facebook AI Research (now Meta AI), with key contributors including Soumith Chintala, Adam Paszke, and Sam Gross.
  • Where did it come from? It grew out of the earlier Torch project and was released as an open-source project in 2016.
  • Why do people use it? It makes it easier to experiment with AI ideas and turn trained models into real applications.
Python — Check your PyTorch installation
import torch

print("PyTorch version:", torch.__version__)
print("GPU available:", torch.cuda.is_available())
Example output: PyTorch version: 2.x.x GPU available: True or False (depends on your computer)
In simple words: PyTorch is like a workshop. It gives developers the tools they need to teach computers to recognize patterns and make predictions.
2. What Is a Tensor?
A tensor is a container for numbers. The number of dimensions tells us how the numbers are arranged. You can think of it as a spreadsheet that can extend beyond rows and columns.
  • 0-D tensor — one number: Like storing a student's age.
  • 1-D tensor — a list: Like storing marks for several students.
  • 2-D tensor — rows and columns: Like a table of student marks.
  • 3-D tensor — a group of tables: Like several tables stacked together.
Python — Create tensors of different dimensions
import torch

single_number = torch.tensor(5)
number_list = torch.tensor([10, 20, 30])
table = torch.tensor([[10, 20], [30, 40]])

print("0-D:", single_number)
print("1-D:", number_list)
print("2-D:\n", table)
Example output: 0-D: tensor(5) 1-D: tensor([10, 20, 30]) 2-D: tensor([[10, 20], [30, 40]])
Remember: A tensor is not limited to a normal table. It can hold data in one, two, three, or even many dimensions.
3. What Is the Main Purpose of PyTorch Tensors?
Tensors give PyTorch a consistent way to store data and perform mathematical operations on it. They are designed to work efficiently with computer processors and graphics cards.
  • Store data: Hold information that an AI model receives, such as image pixels, words converted into numbers, or sales figures.
  • Perform calculations: Add, multiply, compare, and transform large groups of numbers.
  • Work with GPUs: Send suitable calculations to a GPU so many operations can happen in parallel.
  • Support learning: Keep track of calculations so PyTorch can work out how model settings should change to reduce errors.
Python — Basic tensor calculation
import torch

x = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
y = x * 2 + 3
z = y.mean()

print("Original tensor:\n", x)
print("Calculated average:", z.item())
Output: Original tensor: tensor([[1., 2.], [3., 4.]]) Calculated average: 8.0
4. Where Are PyTorch Tensors Used?
Tensors are used throughout an AI project, from the moment data enters a model until the model produces an answer.
  • Images and videos: Store pixel values so a model can identify objects, faces, or scenes.
  • Text and language: Store numerical representations of words and sentences for language models.
  • Model parameters: Store the weights and bias values that a neural network learns during training.
  • Scientific calculations: Help with statistics, signal processing, and other number-heavy tasks.
Python — A tiny model calculation
import torch

# 3 examples, each with 4 input values
inputs = torch.randn(3, 4)
weights = torch.randn(4, 1)

# Calculate one output for each example
outputs = torch.matmul(inputs, weights)

print("Output shape:", outputs.shape)
Output: Output shape: torch.Size([3, 1])
5. How Does Automatic Differentiation Help AI Learn?
Imagine learning to throw a ball into a basket. You try, see how far you missed, adjust your aim, and try again. An AI model learns in a similar way: it makes a prediction, measures its error, and adjusts its internal values.
  • Forward calculation: The model uses its current values to make a prediction.
  • Measure the error: A loss function calculates how far the prediction is from the correct answer.
  • Calculate gradients: PyTorch's automatic differentiation system (Autograd) calculates how each model value contributed to the error.
  • Update and repeat: A training algorithm uses those gradients to adjust the model and improve future predictions.
Python — Autograd in a small example
import torch

x = torch.tensor(2.0, requires_grad=True)
y = x * x + 3 * x

y.backward()

print("Result:", y.item())
print("Gradient:", x.grad.item())
Output: Result: 10.0 Gradient: 7.0
Layman meaning: Autograd works out the direction and amount of change needed for a model's values. This helps the model learn from its mistakes.
6. Key Benefits of PyTorch Tensors
These features make PyTorch useful for both experimenting with AI and building practical applications.
  • Flexible calculations: PyTorch builds its calculation steps as the program runs. This makes many models easier to experiment with and debug.
  • NumPy compatibility: PyTorch can work with NumPy arrays, making it easier to use Python's scientific-computing tools.
  • Python-friendly: Its syntax and workflow feel familiar to people who already know Python.
  • Hardware acceleration: Tensors can use supported GPUs and other accelerators for faster calculations.
  • Large ecosystem: Libraries such as torchvision and torchaudio extend PyTorch for images, audio, and other tasks.
Python — Convert between NumPy and PyTorch
import torch
import numpy as np

values = np.array([1.5, 2.5, 3.5])
tensor_values = torch.from_numpy(values)

print("PyTorch tensor:", tensor_values)
print("Back to NumPy:", tensor_values.numpy())
Output: PyTorch tensor: tensor([1.5000, 2.5000, 3.5000], dtype=torch.float64) Back to NumPy: [1.5 2.5 3.5]
7. Quick Revision — Remember These Three Terms
  • PyTorch: A toolbox used to build and train AI models.
  • Tensor: An organized container for numbers and data.
  • Autograd: The PyTorch feature that automatically calculates gradients to help a model learn.
Big picture: PyTorch stores information in tensors, performs calculations on that information, and uses Autograd to help improve a model during training.