在PyTorch张量中,我想从输入中获取输出,如下所示:
如何在Pytroch中实现这种填充?
答案 0 :(得分:0)
一种实现方法是
def my_odd_padding(list_of_2d_tensors, pad_value):
# get the sizes of the matrices
hs = [t_.shape[0] for t_ in list_of_2d_tensors]
ws = [t_.shape[1] for t_ in list_of_2d_tensors]
# allocate space for output
result = torch.zeros(sum(hs), sum(ws))
result.add_(pad_value)
fh = 0
fw = 0
for i, t_ in enumerate(list_of_2d_tensors):
result[fh:fh+hs[i], fw:fw+ws[i]] = t_
fh += hs[i]
fw += ws[i]
return result
假设list_of_2d_tensors
上的所有张量都相同,并且在同一dtype
上,当使用{进行分配时,可以将此dtype和设备明确设置为device
。 {3}}