Last active
July 7, 2023 17:07
-
-
Save NegatioN/acbd8bb6be866ce1831b2d073fd7c450 to your computer and use it in GitHub Desktop.
PyTorch Multi-dimensional One hot encoding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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