【发布时间】:2021-04-02 02:32:20
【问题描述】:
如何在 Pytorch 中将标签向量转换为 one-hot 编码并返回?
在经历了整个论坛讨论之后,问题的解决方案被复制到这里,而不是仅仅通过谷歌搜索找到一个简单的解决方案。
【问题讨论】:
-
我真的不明白创建一个线程来复制粘贴另一个论坛的解决方案的意义。
标签: python pytorch one-hot-encoding multiclass-classification
如何在 Pytorch 中将标签向量转换为 one-hot 编码并返回?
在经历了整个论坛讨论之后,问题的解决方案被复制到这里,而不是仅仅通过谷歌搜索找到一个简单的解决方案。
【问题讨论】:
标签: python pytorch one-hot-encoding multiclass-classification
import torch
import numpy as np
labels = torch.randint(0, 10, (10,))
# labels --> one-hot
one_hot = torch.nn.functional.one_hot(target)
# one-hot --> labels
labels_again = torch.argmax(one_hot, dim=1)
np.testing.assert_equals(labels.numpy(), labels_again.numpy())
【讨论】: