Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting tensor to one hot encoded tensor of indices

I have my label tensor of shape (1,1,128,128,128) in which the values might range from 0,24. I want to convert this to one hot encoded tensor, using the nn.fucntional.one_hot function

n = 24
one_hot = torch.nn.functional.one_hot(indices, n)

but this expects a tensor of indices, honestly, I am not sure how to get those. The only tensor I have is the label tensor of the shape described above and it contains values ranging from 1-24, not the indices

How can I get a tensor of indices from my tensor? Thanks in advance.

like image 373
Ryan Avatar asked Jun 09 '19 09:06

Ryan


People also ask

What is one hot encoded tensors?

One hot tensor is a Tensor in which all the values at indices where i =j and i!= j is same. Method Used: one_hot: This method accepts a Tensor of indices, a scalar defining depth of the one hot dimension and returns a one hot Tensor with default on value 1 and off value 0. These on and off values can be modified.

How do you make one hot encoding in PyTorch?

Creating PyTorch one-hot encoding In the above example, we try to implement the one hot() encoding function as shown here first; we import all required packages, such as a torch. After that, we created a tenor with different values, and finally, we applied the one hot() function as shown.

What does TF One_hot do?

The tf. one_hot operation takes a list of category indices and a depth (for our purposes, essentially a number of unique categories), and outputs a One Hot Encoded Tensor. You'll notice a few key differences though between OneHotEncoder and tf.

Can you index a tensor?

Single element indexing for a 1-D tensors works mostly as expected. Like R, it is 1-based. Unlike R though, it accepts negative indices for indexing from the end of the array. (In R, negative indices are used to remove elements.)


1 Answers

If the error you are getting is this one:

Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
RuntimeError: one_hot is only applicable to index tensor.

Maybe you just need to convert to int64:

import torch

# random Tensor with the shape you said
indices = torch.Tensor(1, 1, 128, 128, 128).random_(1, 24)
# indices.shape => torch.Size([1, 1, 128, 128, 128])
# indices.dtype => torch.float32

n = 24
one_hot = torch.nn.functional.one_hot(indices.to(torch.int64), n)
# one_hot.shape => torch.Size([1, 1, 128, 128, 128, 24])
# one_hot.dtype => torch.int64

You can use indices.long() too.

like image 59
Berriel Avatar answered Sep 19 '22 03:09

Berriel