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

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

猜你喜欢

转载自blog.csdn.net/weixin_39190382/article/details/114433884
今日推荐