1 hot encoding in pytorch

I have a set of ID labels from 0…24 that encodes 19 classes and I want basically to have a 1 hot encoding of them: if I use :
target = torch.sparse.torch.eye(19).index_select(dim=0, index=target)
I get index out of range which I completely understand since some labels are 24 (but the number of total classes is 19), strange but the data set is built this way., and if I use:
targets=torch.nn.functional.one_hot(targets)
I get a tensor of 18 columns instead of 19, does anyone knows how to solve this?
even if I set nbr classes to 19 this still blocks due to the fact that some labels are 24 but refers to another lower class
Thanks in advance.

You could map the current class indices from [0, 24] to the expected range [0, 18] for 19 classes, since your use case would otherwise work with 25 classes where some might never be used.

1 Like