Welcome back! Last time you learned to create tensors in PyTorch. Now let's master accessing and extracting specific parts of your tensors.
Indexing and slicing are like having GPS coordinates for your data – you can pinpoint exactly what you need from any tensor.
Engagement Message
Ready to become a tensor navigation expert?
Let's start with basic indexing. Just like Python lists, tensors use square brackets with zero-based indexing.
For a 1D tensor tensor = torch.tensor([10, 20, 30, 40])
, tensor[0]
gives you 10
and tensor[2]
gives you 30
.
Engagement Message
What would tensor[-1]
return in this example?
For 2D tensors, you need two indices: [row, column]
.
With tensor = torch.tensor([[1, 2, 3], [4, 5, 6]])
, tensor[0, 1]
gets the first row, second column (value 2
).
Engagement Message
What would tensor[1, 0]
return from this tensor?
Slicing extracts ranges using the colon :
notation. It works just like Python list slicing.
tensor[1:3]
gets elements from index 1 up to (but not including) index 3. tensor[:2]
gets the first 2 elements.
Engagement Message
Using slicing, how would you retrieve the last three elements of a tensor?
Multi-dimensional slicing combines indexing and slicing. For a 2D tensor, tensor[0, :]
gets the entire first row, while tensor[:, 1]
gets the entire second column.
This is incredibly useful for extracting features or samples from your data.
Engagement Message
Which slice returns all rows but only the first two columns?
Here's a practical example with a small dataset:
data[1:3, 0:2]
extracts a 2x2 subregion: [[4, 5], [7, 8]]
.
Engagement Message
What shape would data[:2, 1:]
produce?
You can also modify tensor values through indexing. This is perfect for data preprocessing or applying masks.
tensor[0] = 99
changes the first element. tensor[:, 0] = 0
sets the entire first column to zero.
Engagement Message
What's one practical reason you might zero out a region of a tensor?
Type
Fill In The Blanks
Markdown With Blanks
Let's practice tensor slicing! Given this tensor, fill in the correct slicing syntax:
Suggested Answers
- 1
- -1
- 2
- 0
