Onehot matrix generation using scatter_

import numpy
import torch
wine_path = "https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv"
wineq_numpy = numpy.loadtxt(wine_path, dtype=numpy.float32, delimiter=";",skiprows=1)

wineq=torch.from_numpy(wineq_numpy)


target=wineq[:,-1]
target = target.unsqueeze(-1)
print(target.shape)
print(target_onehot.shape)

target_onehot = torch.FloatTensor(target.shape[0], 10)
target_onehot.zero_()
target_onehot.scatter_(1, target, 1)

Gives error

RuntimeError                              Traceback (most recent call last)

<ipython-input-192-2622c1acffeb> in <module>()
      1 target_onehot = torch.FloatTensor(target.shape[0], 10)
      2 target_onehot.zero_()
----> 3 target_onehot.scatter_(1, target, 1)

RuntimeError: index 4668431376536567808 is out of bounds for dimension 1 with size 10


I don’t get it why its throwing this error ?

I reckon this is the way ?
i tried in doing by generating random values it works.

import torch

batch_size = 5
nb_digits = 10
# Dummy input that HAS to be 2D for the scatter (you can use view(-1,1) if needed)
y = torch.LongTensor(batch_size,1).random_() % nb_digits
# One hot encoding buffer that you create out of the loop and just keep reusing
y_onehot = torch.FloatTensor(batch_size, nb_digits)

# In your for loop
y_onehot.zero_()
y_onehot.scatter_(1, y, 1)

print(y)

Hi,
label or target has to be LongTensor not Float.

Here, target is float and you need to convert it to long using .long()

PS. it would be great if you could use more descriptive title such as onehot matrix generation using scatter_, it help people to interact with questions easier.

Bests

Oh got it. Thank you so much