【问题标题】:How to convert one-hot vector to label index and back in Pytorch?如何在 Pytorch 中将 one-hot 向量转换为标签索引并返回?
【发布时间】:2021-04-02 02:32:20
【问题描述】:

如何在 Pytorch 中将标签向量转换为 one-hot 编码并返回?

在经历了整个论坛讨论之后,问题的解决方案被复制到这里,而不是仅仅通过谷歌搜索找到一个简单的解决方案。

【问题讨论】:

标签: python pytorch one-hot-encoding multiclass-classification


【解决方案1】:

来自the Pytorch forums

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())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 2019-08-28
    • 2020-10-10
    • 2017-07-27
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    相关资源
    最近更新 更多