💡 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.
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)
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)
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)
(B, C, H, W) and standard computer vision display libraries like Matplotlib or OpenCV which expect channels-last format (B, H, W, C).
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)
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)