假设我有一个数组0,2,我想输出一个由基于0,2的一个热向量组成的矩阵,如[ 1,0,0] (请注意,输出矩阵的第二维假设为3,但它可以是大于argmax(0,2)的任何数字,即2。
我只能想到用这种方式来实现这个功能。有没有更简单的方法。
t = torch.tensor([0,2])
dim2_size = 3
id_t = torch.zeros(t.shape[0], dim2_size)
row_idx = 0
for i in t:
col_idx = i.item()
id_t[row_idx, col_idx] = 1
row_idx += 1
id_t发布于 2020-04-29 06:52:05
这个没有使用任何循环。
import torch
labels = torch.tensor([0, 2])
one_hot = torch.zeros(labels.shape[0], torch.max(labels)+1)
one_hot[torch.arange(labels.shape[0]), labels] = 1
print(one_hot)tensor([[1., 0., 0.],
[0., 0., 1.]])发布于 2020-04-29 09:01:46
通过numpy的方法更加简单
import torch
import numpy as np
labels =[0,2]
output=np.eye(max(labels)+1)[labels]
print(torch.from_numpy(output))发布于 2020-04-29 11:05:41
在Pytorch中,这最好通过使用scatter_来完成。
t = torch.tensor([0,2]).unsqueeze(0)
num_dims = 3
id_t = torch.zeros(num_dims, t.shape[1]).scatter_(0, t, 1)这将为您提供id_t为:
tensor([[1., 0.],
[0., 0.],
[0., 1.]])https://stackoverflow.com/questions/61490959
复制相似问题