我如何将转换应用于火炬张量

How can I apply a transformation to a torch tensor

我有一个 Torch 张量 z,我想将变换矩阵 mat 应用到 z 并使输出与 z 的大小完全相同.这是我的代码 运行:

def trans(z):
    print(z)
    mat = transforms.Compose([transforms.ToPILImage(),transforms.RandomRotation(90),transforms.ToTensor()])
    z = Variable(mat(z.cpu()).cuda())
    z = nnf.interpolate(z, size=(28, 28), mode='linear', align_corners=False)
    return z
z = trans(z)

但是,我得到这个错误:

RuntimeError                              Traceback (most recent call last)
<ipython-input-12-e2fc36889ba5> in <module>()
      3 inputs,targs=next(iter(tst_loader))
      4 recon, mean, var = vae.predict(model, inputs[img_idx])
----> 5 out = vae.generate(model, mean, var)

4 frames
/content/vae.py in generate(model, mean, var)
     90     z = trans(z)
     91     z = Variable(z.cpu().cuda())
---> 92     out = model.decode(z)
     93     return out.data.cpu()
     94 

/content/vae.py in decode(self, z)
     56 
     57     def decode(self, z):
---> 58         out = self.z_develop(z)
     59         out = out.view(z.size(0), 64, self.z_dim, self.z_dim)
     60         out = self.decoder(out)

/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
    720             result = self._slow_forward(*input, **kwargs)
    721         else:
--> 722             result = self.forward(*input, **kwargs)
    723         for hook in itertools.chain(
    724                 _global_forward_hooks.values(),

/usr/local/lib/python3.6/dist-packages/torch/nn/modules/linear.py in forward(self, input)
     89 
     90     def forward(self, input: Tensor) -> Tensor:
---> 91         return F.linear(input, self.weight, self.bias)
     92 
     93     def extra_repr(self) -> str:

/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in linear(input, weight, bias)
   1674         ret = torch.addmm(bias, input, weight.t())
   1675     else:
-> 1676         output = input.matmul(weight.t())
   1677         if bias is not None:
   1678             output += bias

RuntimeError: mat1 dim 1 must match mat2 dim 0

如何才能成功应用此旋转变换 mat 并且不会出现任何错误?

谢谢, 文尼

问题是 interpolate 需要一个批处理维度,但根据错误消息和 transforms 的成功应用,您的数据似乎没有。由于您的输入是空间的(基于 size=(28, 28)),您可以通过添加批处理维度并更改 mode 来解决这个问题,因为 linearnot implemented 的空间输入:

z = nnf.interpolate(z.unsqueeze(0), size=(28, 28), mode='bilinear', align_corners=False)

如果你希望z仍然有像(C, H, W)这样的形状,那么:

z = nnf.interpolate(z.unsqueeze(0), size=(28, 28), mode='bilinear', align_corners=False).squeeze(0)