美文网首页
pytorch学习笔记-one_hot的用法

pytorch学习笔记-one_hot的用法

作者: 升不上三段的大鱼 | 来源:发表于2022-12-22 09:23 被阅读0次

如果想把一个tensor转成 onehot 形式,可以用 torch.nn..functional.one_hot

如果出现了错误:

RuntimeError: one_hot is only applicable to index tensor.

你需要把tensor转成 int64或者long

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

来源:https://stackoverflow.com/questions/56513576/converting-tensor-to-one-hot-encoded-tensor-of-indices

相关文章

网友评论

      本文标题:pytorch学习笔记-one_hot的用法

      本文链接:https://www.haomeiwen.com/subject/txjvqdtx.html