Sizes of tensors must match except in dimension 1. Expected size 24 but got size 25 for tensor numbe

Posted AI浩

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Sizes of tensors must match except in dimension 1. Expected size 24 but got size 25 for tensor numbe相关的知识,希望对你有一定的参考价值。

在做图像分割的时候遇到了错误,错误如下:

File "D:/segmentation/Pytorch-UNet-master/train.py", line 193, in <module>
    amp=args.amp)
  File "D:/segmentation/Pytorch-UNet-master/train.py", line 88, in train_net
    masks_pred = net(images)
  File "D:\\ProgramData\\Anaconda3\\envs\\mytorch\\lib\\site-packages\\torch\\nn\\modules\\module.py", line 1110, in _call_impl
    return forward_call(*input, **kwargs)
  File "D:\\ProgramData\\Anaconda3\\envs\\mytorch\\lib\\site-packages\\segmentation_models_pytorch\\base\\model.py", line 16, in forward
    decoder_output = self.decoder(*features)
  File "D:\\ProgramData\\Anaconda3\\envs\\mytorch\\lib\\site-packages\\torch\\nn\\modules\\module.py", line 1110, in _call_impl
    return forward_call(*input, **kwargs)
  File "D:\\ProgramData\\Anaconda3\\envs\\mytorch\\lib\\site-packages\\segmentation_models_pytorch\\unet\\decoder.py", line 121, in forward
    x = decoder_block(x, skip)
  File "D:\\ProgramData\\Anaconda3\\envs\\mytorch\\lib\\site-packages\\torch\\nn\\modules\\module.py", line 1110, in _call_impl
    return forward_call(*input, **kwargs)
  File "D:\\ProgramData\\Anaconda3\\envs\\mytorch\\lib\\site-packages\\segmentation_models_pytorch\\unet\\decoder.py", line 39, in forward
    x = torch.cat([x, skip], dim=1)
RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 24 but got size 25 for tensor number 1 in the list.

从错误的分析得知是维度没有对上。将x和skip的维度打印出来:

torch.Size([2, 448, 24, 18]) torch.Size([2, 160, 25, 18])

这就对应上上面的错误了。
出现这个错误的原因是在输入图片的时候,没有将图像resize成512×512大小,导致维度不一致!
将图片resize后就可以解决。
在打印x和skip的维度:

torch.Size([2, 448, 32, 32]) torch.Size([2, 160, 32, 32])

以上是关于Sizes of tensors must match except in dimension 1. Expected size 24 but got size 25 for tensor numbe的主要内容,如果未能解决你的问题,请参考以下文章

The size of tensor a must match the size of tensor b at non-singleton dimension 0

The size of tensor a must match the size of tensor b at non-singleton dimension 0

tf.keras遇见的坑:Output tensors to a Model must be the output of a TensorFlow `Layer`

解决ret = umr_sum(arr, axis, dtype, out, keepdims)RuntimeError: The size of tensor a (400) must match

解决ret = umr_sum(arr, axis, dtype, out, keepdims)RuntimeError: The size of tensor a (400) must match(

Pytorch-张量tensor详解(线性回归实战)