在Pytorch中填充

时间:2018-10-24 08:56:29

标签: python pytorch

在PyTorch张量中,我想从输入中获取输出,如下所示:

enter image description here

如何在Pytroch中实现这种填充?

1 个答案:

答案 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}}