Is there something like "keras.utils.to_categorical" in pytorch

Is there something like “keras.utils.to_categorical” in pytorch

1 Like
def to_categorical(y, num_classes):
    """ 1-hot encodes a tensor """
    return np.eye(num_classes, dtype='uint8')[y]
10 Likes

Thnx, it works great.

Is this the expected solution in pytorch to build categorical tensors?

Better yet, you can use the code directly from Keras: https://github.com/keras-team/keras/blob/master/keras/utils/np_utils.py#L9-L37

Dude, your code is awesome! How do you think up that. :+1:

amazing! I am still learning the advanced indexing.

How did that work? What kind of sorcery is that? How is that kind of indexing possible. Could you link me to a useful resource?

This code works! y is a 1D NumPy array holding the class number of the samples.

temp_outs = numpy.zeros((y.shape[0], numpy.unique(y).size), dtype=numpy.uint8)
temp_outs[numpy.arange(y.shape[0]), numpy.uint8(y)] = 1

y = temp_outs

How about

import torch
import torch.nn.functional as F
x = torch.tensor([1, 0])
F.one_hot(x, num_classes=2)

?

1 Like