RuntimeError: Sizes of tensors must match except in dimension 1. Got 61 and 60 in dimension 2

在使用PyTorch训练语义分割模型时遇到RuntimeError,原因是torch.cat操作中张量尺寸不一致。错误源于图像采样和下采样后尺寸不同。解决方法包括确保输入图像尺寸为32的倍数或调整张量至相同尺寸。通过这些调整,可以避免因取整导致的维度不匹配问题。

1. 背景介绍

      在训练语义分割模型时,出现以下错误:

      RuntimeError: Sizes of tensors must match except in dimension 1. Got 61 and 60 in dimension 2

 

2. 错误产生原因

      在模型中有以下操作:torch.cat(x, y)

      当x, y的尺寸不一致时,就会出现以上错误。

      进行单步调试,发现我的错误是因为图像山采样和下采样后,由于取整的方式不一样,导致的x、y的尺寸不一致。

 

3. 解决方法

      方法1:在图像输入时,宽和高最好是32的整数倍,就不会出现取整的问题。

      方法2:把x、y resize到相同的尺寸。

引用\[1\]:在目标检测服务中,使用yolov7模型通过flask打包成预测服务API。训练时,输入的图像大小为1280。如果输入的预测图片大小大于1280,则预测成功;如果小于1280,则会报错RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 27 but got size。根据错误提示,推测问题出在图像处理过程中的resize操作上,具体是在以下代码行出错:pred = self.model(img, augment=self.augment)\[0\]。完整的错误提示如下: RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 48 but got size 47 for tensor number 1 in the list. 引用\[2\]中给出了改造base64_to_image函数的代码,该函数用于将base64格式的图片转换为图片对象。在这个函数中,使用了cv2库对图片进行解码和处理。引用\[3\]分析了问题的原因,发现是在pading过程中少给了一个参数stride,导致小图片在pading过程中像素错误,从而导致了dimension错误。 解决方案是在图像处理过程中正确设置stride参数,确保图片的像素处理正确。 #### 引用[.reference_title] - *1* *2* *3* [记录解决RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 27 but got ...](https://blog.csdn.net/h363924219/article/details/127778425)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CV-deeplearning

请博主加个火腿

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值