IndexError: index_select(): Index is supposed to be a vector

Viewed 3181
    for batch_id, (data, target) in enumerate(tqdm(train_loader)):
        print(target)
        print('Entered for loop')
        target = torch.sparse.torch.eye(10).index_select(dim=0, index=target)
        data, target = Variable(data), Variable(target)

The line which contains the index_select function gives this error and I am not able to find a solution to it anywhere. The target variable on printing looks like this:

tensor([[4],
[1],
[8],
[5],
[9],
[5],
[5],
[8],
[4],
[6]])

How do I convert the target variable into a vector? Isn’t it already a vector?

1 Answers

If you would look at the shape of your target variable, you would find that it is a 2D tensor of shape:

target.shape # torch.Size([10, 1])

Error message is a bit confusing, but in essence index should be a 1D tensor (vector). So using .squeeze method would make:

target.squeeze().shape # torch.Size([10])

and index_select method would not complain.

Related