Skip to content

Instantly share code, notes, and snippets.

@NegatioN
Last active July 7, 2023 17:07
Show Gist options
  • Save NegatioN/acbd8bb6be866ce1831b2d073fd7c450 to your computer and use it in GitHub Desktop.
Save NegatioN/acbd8bb6be866ce1831b2d073fd7c450 to your computer and use it in GitHub Desktop.
PyTorch Multi-dimensional One hot encoding
def _to_one_hot(y, num_classes):
scatter_dim = len(y.size())
y_tensor = y.view(*y.size(), -1)
zeros = torch.zeros(*y.size(), num_classes, dtype=y.dtype)
return zeros.scatter(scatter_dim, y_tensor, 1)
print(_to_one_hot(torch.as_tensor([2, 4, 7]), num_classes=10))
print(_to_one_hot(torch.as_tensor([[1, 5 ,6], [2, 4, 7]]), num_classes=10))
print(_to_one_hot(torch.as_tensor([[[1, 5 ,6], [2, 4, 7]], [[1, 5 ,6], [2, 4, 7]]]), num_classes=10))
'''
tensor([[ 0., 0., 1., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 1., 0., 0.]], device='cuda:0')
tensor([[[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 1., 0., 0., 0.]],
[[ 0., 0., 1., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 1., 0., 0.]]], device='cuda:0')
tensor([[[[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 1., 0., 0., 0.]],
[[ 0., 0., 1., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 1., 0., 0.]]],
[[[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 1., 0., 0., 0.]],
[[ 0., 0., 1., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 1., 0., 0.]]]], device='cuda:0')
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment