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.

💡 Real-World Context: E-Commerce Image Batch Normalization

Imagine you are building an AI-powered image moderation pipeline for an online retail platform. Your model receives incoming batches of product photographs. Each batch is represented as a 4D tensor with shape (Batch_Size = 3, Channels = 3, Height = 224, Width = 224).

To normalize pixel values across RGB channels, you need to subtract channel-specific mean values and divide by standard deviations. This requires precise multi-dimensional indexing, slicing, dimension squeezing, and broadcasting mechanics to automatically align a 1D channel tensor across 4D spatial batches without writing explicit loops.

📸 Visual Walkthrough: Tensor Operations on Product Images

Use this visual overview to connect tensor operations with familiar e-commerce image tasks: selecting an image, cropping a region, reshaping pixel data, applying RGB channel values, and changing dimension order.

Educational infographic showing PyTorch tensor operations using sneaker product images: indexing, slicing, reshaping, RGB broadcasting, and permuting dimensions.
Figure: Real-world visual guide to common tensor operations. The code examples below show the corresponding PyTorch operations and tensor shapes.
1. Basic Tensor Indexing and Slicing
Extracting specific image samples, color channels, and regional bounding boxes from a multi-dimensional tensor using Python-style zero-based indexing and slicing.
Python (tensor_indexing.py)
import torch

# Simulate a batch of 3 RGB images: (Batch=3, Channels=3, Height=4, Width=4)
torch.manual_seed(42)
image_batch = torch.randint(0, 256, (3, 3, 4, 4), dtype=torch.float32)

print("Full Batch Shape:", image_batch.shape)

# 1. Extract the 1st image in the batch
first_image = image_batch[0]
print("First Image Shape (C, H, W):", first_image.shape)

# 2. Extract only the Red channel (Channel index 0) for all images
red_channels = image_batch[:, 0, :, :]
print("Red Channels Shape (B, H, W):", red_channels.shape)

# 3. Crop a 2x2 center region across all images and channels (H: 1 to 3, W: 1 to 3)
center_crop = image_batch[:, :, 1:3, 1:3]
print("Center Crop Shape (B, C, H_crop, W_crop):", center_crop.shape)
Output: Full Batch Shape: torch.Size([3, 3, 4, 4]) First Image Shape (C, H, W): torch.Size([3, 4, 4]) Red Channels Shape (B, H, W): torch.Size([3, 4, 4]) Center Crop Shape (B, C, H_crop, W_crop): torch.Size([3, 3, 2, 2])
2. Reshaping and Dimension Manipulation (`reshape`, `view`, `squeeze`)
Flattening spatial feature maps into dense vectors for fully connected classification layers, and removing singleton dimensions.
Python (tensor_reshape.py)
import torch

# Feature map output from a convolutional layer: (Batch=2, Channels=64, Height=7, Width=7)
conv_output = torch.randn(2, 64, 7, 7)
print("Original Conv Output Shape:", conv_output.shape)

# Flatten spatial dimensions for a Linear Dense Layer: (Batch, Features) -> (2, 64 * 7 * 7 = 3136)
flattened = conv_output.reshape(conv_output.size(0), -1)
print("Flattened Feature Vector Shape:", flattened.shape)

# Demonstrate squeeze and unsqueeze
singleton_tensor = torch.tensor([[[3.14]]]) # Shape: (1, 1, 1)
print("Original Singleton Shape:", singleton_tensor.shape)

squeezed = singleton_tensor.squeeze()
print("Squeezed Shape:", squeezed.shape)

unsqueezed = squeezed.unsqueeze(0) # Add batch dimension back: Shape (1,) -> (1, 1)
print("Unsqueezed Shape:", unsqueezed.shape)
Output: Original Conv Output Shape: torch.Size([2, 64, 7, 7]) Flattened Feature Vector Shape: torch.Size([2, 3136]) Original Singleton Shape: torch.Size([1, 1, 1]) Squeezed Shape: torch.Size([]) Unsqueezed Shape: torch.Size([1, 1])
3. Tensor Broadcasting Rules in Action
Applying arithmetic operations between tensors of different shapes by virtually expanding dimensions from right to left without allocating duplicate memory.
Python (tensor_broadcasting.py)
import torch

# Real-world e-commerce example: Normalizing RGB channels across a batch of images
# Image batch: (Batch=2, Channels=3, Height=2, Width=2)
images = torch.ones(2, 3, 2, 2) * 100.0 # Pixel value 100 across all channels

# Channel-specific mean values to subtract: (3,) -> represents [R_mean, G_mean, B_mean]
channel_means = torch.tensor([10.0, 50.0, 90.0])

# Broadcasting Error Prevention: 
# To broadcast channel_means (shape: 3) across images (shape: 2, 3, 2, 2),
# we must reshape channel_means to align with trailing dimensions: (1, 3, 1, 1)
channel_means_reshaped = channel_means.view(1, 3, 1, 1)

# Perform broadcasting subtraction
normalized_images = images - channel_means_reshaped

print("Original Image Pixel [0, 1, 0, 0]:", images[0, 1, 0, 0].item())
print("Channel 1 Mean Subtracted:", channel_means[1].item())
print("Normalized Pixel [0, 1, 0, 0]:", normalized_images[0, 1, 0, 0].item())
print("Normalized Batch Shape:", normalized_images.shape)
Output: Original Image Pixel [0, 1, 0, 0]: 100.0 Channel 1 Mean Subtracted: 50.0 Normalized Pixel [0, 1, 0, 0]: 50.0 Normalized Batch Shape: torch.Size([2, 3, 2, 2])
4. Permuting and Transposing Dimensions (`permute`, `transpose`)
Converting between PyTorch's standard channels-first format (B, C, H, W) and standard computer vision display libraries like Matplotlib or OpenCV which expect channels-last format (B, H, W, C).
Python (tensor_permute.py)
import torch

# PyTorch standard tensor layout: (Batch=1, Channels=3, Height=32, Width=32)
pytorch_tensor = torch.randn(1, 3, 32, 32)
print("PyTorch Layout (B, C, H, W):", pytorch_tensor.shape)

# Convert to Channels-Last layout for visualization: (Batch, Height, Width, Channels) -> (1, 32, 32, 3)
display_tensor = pytorch_tensor.permute(0, 2, 3, 1)
print("Display Layout (B, H, W, C):", display_tensor.shape)

# Transpose specific dimensions (e.g., swapping Height and Width)
transposed = pytorch_tensor.transpose(2, 3)
print("Transposed H & W Shape:", transposed.shape)
Output: PyTorch Layout (B, C, H, W): torch.Size([1, 3, 32, 32]) Display Layout (B, H, W, C): torch.Size([1, 32, 32, 3]) Transposed H & W Shape: torch.Size([1, 3, 32, 32])
5. Concatenation and Stacking (`cat`, `stack`)
Combining separate image batches or feature vectors along existing or brand new tensor dimensions.
Python (tensor_concat_stack.py)
import torch

# Two separate image batches, each of shape (Batch=2, Channels=3, Height=8, Width=8)
batch_a = torch.randn(2, 3, 8, 8)
batch_b = torch.randn(2, 3, 8, 8)

# 1. Concatenate along batch dimension (dim=0) -> Result shape: (4, 3, 8, 8)
concatenated = torch.cat([batch_a, batch_b], dim=0)
print("Concatenated Shape (dim=0):", concatenated.shape)

# 2. Stack along a new dimension (dim=0) -> Result shape: (2, 2, 3, 8, 8)
stacked = torch.stack([batch_a, batch_b], dim=0)
print("Stacked Shape (new dim=0):", stacked.shape)
Output: Concatenated Shape (dim=0): torch.Size([4, 3, 8, 8]) Stacked Shape (new dim=0): torch.Size([2, 2, 3, 8, 8])