Lesson 6 : Chapter 6 (Other Computer Vision Problems)

What does the [0] at the end of the following code mean : idxs = torch.where(dsets.train[0][1]==1.)[0]
When I remove the [0] from the code an error results stating “ValueError: only one element tensor can be converted to Python scalars.”

In Python, the brackets used like that are used for indexing into containers.

For example when you have a list of things:

colours = ["red", "green", "blue"]
favourite = colours[0]
# now favourite is equal to "red"
print(favourite)

Above we used the indexing (colours[0]) to get the first thing in colours.

Indexing starts from 0 so:

colours[0] # first colour which is red
colours[1] # second colour which is green
colours[2] # third colour which is blue

Now let’s get to the specific thing that your piece of code is indexing into.
https://pytorch.org/docs/stable/generated/torch.where.html

Above is some docs for what torch.where function does but the important part for now is that it gives back a Tensor. A Tensor is similar to a normal python list but it can only hold one kind of thing and it can’t grow or shrink. Pytorch uses it to hold numbers for doing fast calculations.

So doing idxs = torch.where(dsets.train[0][1]==1.)[0] is the same as:

some_tensor = torch.where(dsets.train[0][1]==1.)
idxs = some_tensor[0] # index into the tensor

The thing is tensors aren’t always just lists of numbers they can be lists of lists of numbers aka 3d or even higher dimensions.

You can check what the shape of the tensor is with:

print(some_tensor.shape)
# then you can see what its shape is once you indexed into it
print(some_tensor[0].shape)

There is more to understanding indexing tensors so here is a good blog post to start you off: