在 Torch 中,我如何从整数标签列表创建一个 1-hot 张量?
In Torch how do I create a 1-hot tensor from a list of integer labels?
我有一个整数 class 标签的字节张量,例如来自 MNIST 数据集。
1
7
5
[torch.ByteTensor of size 3]
如何使用它来创建 1-hot 向量的张量?
1 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 1 0 0 0 0 0
[torch.DoubleTensor of size 3x10]
我知道我可以用一个循环来做到这一点,但我想知道是否有任何聪明的 Torch 索引可以在一行中为我获取它。
indices = torch.LongTensor{1,7,5}:view(-1,1)
one_hot = torch.zeros(3, 10)
one_hot:scatter(2, indices, 1)
您可以在 torch/torch7 github readme(主分支)中找到 scatter
的文档。
另一种方法是打乱单位矩阵中的行:
indicies = torch.LongTensor{1,7,5}
one_hot = torch.eye(10):index(1, indicies)
这不是我的主意,我在 karpathy/char-rnn 中找到了它。
我有一个整数 class 标签的字节张量,例如来自 MNIST 数据集。
1
7
5
[torch.ByteTensor of size 3]
如何使用它来创建 1-hot 向量的张量?
1 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 1 0 0 0 0 0
[torch.DoubleTensor of size 3x10]
我知道我可以用一个循环来做到这一点,但我想知道是否有任何聪明的 Torch 索引可以在一行中为我获取它。
indices = torch.LongTensor{1,7,5}:view(-1,1)
one_hot = torch.zeros(3, 10)
one_hot:scatter(2, indices, 1)
您可以在 torch/torch7 github readme(主分支)中找到 scatter
的文档。
另一种方法是打乱单位矩阵中的行:
indicies = torch.LongTensor{1,7,5}
one_hot = torch.eye(10):index(1, indicies)
这不是我的主意,我在 karpathy/char-rnn 中找到了它。