当前位置:   article > 正文

生成器报错,RuntimeError: Sizes of tensors must match except in dimension

runtimeerror: sizes of tensors must match except in dimension 1. expected si

RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 2 but got size 3 for tensor number 1 in the list.

常见的模型报错,比方说pix2pix模型

In[18], line 84, in Generator.forward(self, x)

        82 bottleneck = self.bottleneck(d7)

        83 up1 = self.up1(bottleneck)

---> 84 up2 = self.up2(torch.cat([up1, d7], 1))

        85 up3 = self.up3(torch.cat([up2, d6], 1))

        86 up4 = self.up4(torch.cat([up3, d5], 1))

RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 2 but got size 3 for tensor number 1 in the list.

解决方案:

模型里面加一个函数

  1. from torch import nn
  2. import torch.nn.functional as F
  3. class Generator(nn.Module):
  4. def __init__(self,*args):
  5. self.padder_size = 256
  6. '''
  7. 模型该长啥样长啥样
  8. '''
  9. def forward(self,inp):
  10. B,C,H,W = inp.shape
  11. inp = self.check_image_size(inp)
  12. '''
  13. 该怎么forward怎么forward
  14. '''
  15. return x[:,:,:H,:W]
  16. def check_image_size(self, x):
  17. _, _, h, w = x.size()
  18. mod_pad_h = (self.padder_size - h % self.padder_size) % self.padder_size
  19. mod_pad_w = (self.padder_size - w % self.padder_size) % self.padder_size
  20. x = F.pad(x, (0, mod_pad_w, 0, mod_pad_h))
  21. return x

padder_size根据最接近你数据集的来,这个函数是从GitHub - megvii-research/NAFNet: The state-of-the-art image restoration model without nonlinear activation functions.这个模型的代码里找的,本来是做pix2pix但是输入为300*300的时候就报错,256*256就不报错,后面发现是中间反卷积的时候输出形状和下采样的形状不一样,cat就不好使了,上了这个函数就好使了,但是会慢不少。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/149582
推荐阅读
相关标签
  

闽ICP备14008679号