UserWarning: Using a target size (torch.Size([16])) that is different to the input size (torch.Size([16, 1])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.
一、问题描述
报错如下:
UserWarning: Using a target size (torch.Size([16])) that is different to the input size (torch.Size([16, 1])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.
二、问题解决
原因分析,根据报错提示可知,报错原因是目标 tensor 的尺寸和输入 tensor 的尺寸不一致。只是抛出警告,程序还能正常运行。
查看代码,发现目标 tensor 的尺寸是 ‘torch.Size([16, 1])’,而输入 tensor 的尺寸是 ‘torch.Size([16])’。
解决方法:使用 reshape() 函数改变目标 tensor 的尺寸,reshape() 函数具体用法自行查阅。以下是具体操作:
x = x.reshape(-1)
安装上述方法改进之后,果然不再报错!
另一种方法:
x = torch.squeeze(x,1)
采用此种方法也能达到降维的目的,也能解决问题。
类似的问题都可以采用 reshape() 函数或者 squeeze() 函数和 unsqueeze() 函数改变 tensor 的尺寸来解决问题。
参考资料
1.https://blog.csdn.net/a8039974/article/details/119925040
2.https://blog.csdn.net/weixin_42989041/article/details/111992033