Deep Learning with PyTorch / Tensors

Index, slice and reshape tensors

Lesson 5 of 41. Open to read. No account needed.

The Problem: Data Rarely Arrives in the Shape a Layer Wants

A dataset might give you one image as a 28 by 28 grid, but an image layer wants a batch with a channel dimension, (N, 1, 28, 28), and a fully connected layer wants each image as one row of 784 numbers, (N, 784). You will also need to pick out one sample, the images of one class, or the first few rows. This lesson teaches the operations that select parts of a tensor and change its shape, and the one subtlety that trips everyone up: some of them return a view of the same data, not a copy.

Selecting Parts of a Tensor

Indexing works like NumPy. Throughout this lesson, images is a batch of four 28 by 28 "images" with shape (4, 28, 28).

ExpressionSelectsShape
images[0]The first image(28, 28)
images[0, 5]Row 5 of the first image(28,)
images[:, 0]Row 0 of every image(4, 28)
images[1:3]Images 1 and 2 (the end is excluded)(2, 28, 28)
images[labels == 3]Images whose label is 3(k, 28, 28) for k matches

An integer index removes that dimension; a slice such as 1:3 keeps it. A boolean mask, a tensor of True and False values like labels == 3, keeps the entries where it is True, so the size of that dimension depends on how many match.

Combining Tensors: cat and stack

Both join a list of tensors, in different ways:

  • torch.stack([a, b]) adds a new dimension. Two (28, 28) images become (2, 28, 28): a batch of two.
  • torch.cat([a, b]) joins along an existing dimension, 0 by default. Two (28, 28) images become (56, 28): one tall image.

Use stack to build a batch from samples and cat to join two batches ((64, 1, 28, 28) and (32, 1, 28, 28) give (96, 1, 28, 28)).

Changing Shape

OperationEffectExample
reshape(new_shape)Same values, new shape; -1 means "work out this size"(4, 28, 28) → reshape(4, -1) → (4, 784)
flatten(start_dim=1)Merge every dimension from start_dim onwards(4, 1, 28, 28) → (4, 784)
unsqueeze(dim)Insert a dimension of size 1(4, 28, 28) → unsqueeze(1) → (4, 1, 28, 28)
squeeze(dim)Remove a size-1 dimension(4, 1, 28, 28) → squeeze(1) → (4, 28, 28)
t() / transpose(a, b)Swap two dimensions(2, 3) → (3, 2)
permute(order)Reorder all dimensions(4, 1, 28, 28) → permute(0, 2, 3, 1) → (4, 28, 28, 1)

The number of values never changes: (4, 28, 28) has 3,136 values, and so must every shape you reshape it to. PyTorch's image layers use the order batch, channels, height, width, written NCHW. Some image libraries store channels last, which permute converts between.

Pass a dimension to squeeze. Without one, squeeze() removes every size-1 dimension, which can silently remove a batch dimension when the batch happens to contain one sample.

Views, Copies and Contiguity

A storage row holding 0 to 5. The 2 by 3 tensor reads it row by row, so it is contiguous. Its transpose is a 3 by 2 view of the same storage whose rows jump through the data, so it is not contiguous. An orange box says that view(-1) fails on the transpose and reshape(-1) copies the data instead.

Read from the top: one row of stored numbers, then two tensors reading it in different orders.

A tensor's values sit in memory as one long row, its storage. Many operations, including indexing with integers and slices, view, transpose and permute, return a view: a new tensor object that reads the same storage in a different shape or order, without copying (S28). Changing a view changes the original. That is fast, and occasionally surprising.

A tensor is contiguous when reading its elements row by row visits the storage in order. torch.arange(6).reshape(2, 3) is contiguous. Its transpose reads the same storage in the order 0, 3, 1, 4, 2, 5, jumping back and forth, so it is not contiguous. The strides record those jumps: (3, 1) for the original (move 3 places for the next row, 1 for the next column) and (1, 3) for the transpose.

view can only describe the same storage in a new shape. It cannot reorder values, so it fails on a tensor that is not contiguous. reshape returns a view when it can and a copy when it must. PyTorch's documentation says code should not rely on which (S28). If you need an independent copy, use clone(). contiguous() returns a contiguous copy only when the tensor is not already contiguous.

Boolean masks are different. Indexing with a mask or a list of positions is advanced indexing, which always returns a copy, while integer and slice indexing return views (S28). So images[labels == 3] is a copy; changing it leaves images alone.

Exercise: Predict the Shapes

Starting state: the course environment active.

  1. Create the exercise folder. macOS and Linux:

    mkdir -p ~/pytorch-practice/reshape-tensors
    cd ~/pytorch-practice/reshape-tensors
    

    Windows PowerShell:

    mkdir $HOME\pytorch-practice\reshape-tensors
    cd $HOME\pytorch-practice\reshape-tensors
    
  2. Save this as reshape_tensors.py:

    """Predict, then check, the shapes produced by indexing and reshaping."""
    import torch
    
    images = torch.arange(4 * 28 * 28).reshape(4, 28, 28)  # a batch of 4 "images"
    labels = torch.tensor([3, 0, 3, 1])                   # one label per image
    
    print("1", tuple(images[0].shape))
    print("2", tuple(images[:, 0].shape))
    print("3", tuple(images[1:3].shape))
    print("4", tuple(images[labels == 3].shape))
    print("5", tuple(images.unsqueeze(1).shape))
    print("6", tuple(images.reshape(4, -1).shape))
    print("7", tuple(torch.stack([images[0], images[1]]).shape))
    print("8", tuple(torch.cat([images[0], images[1]]).shape))
    
    row = images[0, 0]        # a view: no data is copied
    row[0] = -1
    print("images[0, 0, 0] after changing the view:", images[0, 0, 0].item())
    flipped = images[0].t()   # transpose swaps the two dimensions
    print("transposed shape:", tuple(flipped.shape), "| contiguous:", flipped.is_contiguous())
    
  3. Write down your predicted shape for lines 1 to 8, and the two values on the last lines. Then run:

    python reshape_tensors.py
    

    Output (exact):

    1 (28, 28)
    2 (4, 28)
    3 (2, 28, 28)
    4 (2, 28, 28)
    5 (4, 1, 28, 28)
    6 (4, 784)
    7 (2, 28, 28)
    8 (56, 28)
    images[0, 0, 0] after changing the view: -1
    transposed shape: (28, 28) | contiguous: False
    

Success: at most one wrong prediction, and you can explain each line.

What the Lines Show

  • Lines 1 to 3: an integer index removes a dimension; a slice keeps it.
  • Line 4: two labels equal 3, so the mask keeps two images.
  • Line 5: unsqueeze(1) adds the channel dimension an image layer needs.
  • Line 6: -1 lets PyTorch work out 28 × 28 = 784.
  • Lines 7 and 8: stack makes a batch of two; cat makes one tall image.
  • The view lines: images[0, 0] is a view of row 0 of image 0. Setting its first value to -1 changed images itself. A transposed 28 by 28 image keeps its shape but is no longer contiguous.

Your Turn: A Failing View

Save this as flatten_rows.py in the same folder:

"""Flatten a transposed image into one long row."""
import torch

image = torch.arange(6).reshape(2, 3)
columns_first = image.t()
print(columns_first.view(-1))

Run it. It fails with:

RuntimeError: view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead.

Fix it so it prints the values column by column, and explain why view could not do it.

Clean Up

cd ~/pytorch-practice
ls
rm -r reshape-tensors
ls

Windows PowerShell:

cd $HOME\pytorch-practice
ls
Remove-Item -Recurse reshape-tensors
ls

Check Your Understanding

  1. You have 100 samples each of shape (1, 28, 28) in a Python list. Which operation makes a batch, and what is its shape?
  2. A batch of one image has shape (1, 1, 28, 28). What does squeeze() return, and why is squeeze(1) safer?
  3. You take first = batch[0] and then normalise first in place. Has batch changed?

Answer and Reasoning

Your turn

Replace view(-1) with reshape(-1):

print(columns_first.reshape(-1))

It prints tensor([0, 3, 1, 4, 2, 5]), the values column by column. The transposed tensor reads storage out of order, so its elements cannot be described as one evenly spaced run of the existing storage; view never copies, so it refuses. reshape copies the values into the new order. columns_first.contiguous().view(-1) also works, by making a contiguous copy first.

Understanding check

  1. torch.stack(samples) adds a new first dimension: (100, 1, 28, 28). torch.cat would join along the existing dimension and give (100, 28, 28), losing the channel dimension.
  2. squeeze() removes every size-1 dimension and returns (28, 28), losing both the batch and the channel dimensions. squeeze(1) removes only the channel dimension and returns (1, 28, 28), so the code still works for a batch of any size.
  3. Yes. Integer indexing returns a view, so an in-place change to first changes batch. Use batch[0].clone() if you need an independent copy.

References

36 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy