如何对torch tensor应用变换

4

我有一个Torch Tensor 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并且不出现任何错误呢?
谢谢, Vinny
1个回答

2
问题在于 `interpolate` 函数需要一个批处理维度,但是根据错误信息和成功应用 `transforms` 的情况来看,你的数据似乎没有一个批处理维度。由于你的输入是空间数据(基于 `size=(28, 28)`),因此你可以通过添加批处理维度并更改模式来解决这个问题,因为对于空间输入,`linear` 模式 未实现
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)

1
@VinnyJacobsen 噢,没错... linear 上采样不适用于空间输入。我已经相应地更新了答案。 - Berriel
这让我回到了最初的错误:RuntimeError: mat1 dim 1 must match mat2 dim 0 @Berriel - Vinny Jacobsen
@VinnyJacobsen 这不是最初的错误... 请在 interpolate 调用之前更新问题并附上 z.shape - Berriel
@VinnyJacobsen,正如您所看到的,错误发生在其他地方...因此原始问题已经解决。而且那可能也不是完整的堆栈跟踪。 - Berriel
是的,我会接受你的答案,但我会感激你在这个新错误上的帮助。完整的堆栈跟踪信息已经在问题中提供,请查看一下。@Berriel - Vinny Jacobsen
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接