ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

【pytorch】RuntimeError: 1only batches of spatial targets supported (3D tensors) but got targets of si

2021-03-06 10:59:43  阅读:2775  来源: 互联网

标签:batches 标签 RuntimeError 损失 pytorch https 256 targets


every blog every motto: Just live your life cause we don’t live twice.

0. 前言

在用pytorch训练网络,计算损失时,遇到错误

1. 正文

1.1 错误回顾

RuntimeError: 1only batches of spatial targets supported (3D tensors) but got targets of size: : [2, 10, 256, 256]

上面显示,希望传入一个3维Tensor,结果得到了一个4维的。
代码:

# 损失函数
c_loss = nn.CrossEntropyLoss()
print('预测值:', d0.shape)  
print('标签值: ', labels_v.shape)  

loss0 = c_loss(d0, labels_v.long())

shape:
在这里插入图片描述
说明:

  1. pytorch中Tensor是以 (batch,channel,height,width) 这种方式存储的。
  2. 而在Tensorflow中是以 (batch,height,width,channel) 这种方式存储的。

按照Tensorflow/keras的中计算损失的思维,预测值和标签值的shape是一样的应该可以计算损失才对,为什么会报错呢???
难道pytorch只能计算3维的Tensor???
其实不然……

1.2 解决办法

pytorch和Tensorflow在损失函数计算方面是有细微差别的。
在我们的(十分类)任务中,类似这样:

1.2.1 Tensorflow中

模型训练:
在这里插入图片描述
标签one-hot编码:
在这里插入图片描述
通过这两步,我们就可以计算标签和模型产生的预测结果之间的损失了。

1.2.2 pytorch中

在Pytorch中,我们“不需要”对标签进行one-hot编码,且需要将通道这一维给压缩了。
即:
预测值:(256,256,10)
标签值:(256,256)
即可以直接进行计算损失。
其中,标签中的值为对应的类别数
如下图所示,我们即可以进行损失的计算了
在这里插入图片描述

参考文献

[1] https://discuss.pytorch.org/t/runtimeerror-only-batches-of-spatial-targets-supported-3d-tensors-but-got-targets-of-dimension-4/82098
[2] https://discuss.pytorch.org/t/runtimeerror-1only-batches-of-spatial-targets-supported-3d-tensors-but-got-targets-of-size-1-3-96-128/95030/4
[3] https://pytorch.org/docs/stable/generated/torch.nn.NLLLoss.html
[4] https://www.cnblogs.com/gshang/p/13854889.html
[5] https://jianzhuwang.blog.csdn.net/article/details/110955851

标签:batches,标签,RuntimeError,损失,pytorch,https,256,targets
来源: https://blog.csdn.net/weixin_39190382/article/details/114433884

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有