记录利用CrossEntropyLoss()做图像分割任务踩过的坑~

1、利用unet做图像分割任务时,首先运用BECLoss模型能完全运行成功,但是当损失函数设置为CrossEntropyLoss()是出现如下错误:

1
RuntimeError: 1only batches of spatial targets supported (non-empty 3D tensors) but got targets of size: : [16, 1, 256, 256]

维度问题~~可能是在做分割任务时groundtruth需要的是3维的图片?。。。。。。。。。。。。。。。。不太懂,先降维再说吧,于是就有了

1
labels = labels.squeeze()

然而,报错了。。。。

1
2
3
4
5
6
7
8
9
10
11
/opt/conda/conda-bld/pytorch_1556653183467/work/aten/src/THCUNN/SpatialClassNLLCriterion.cu:103: void cunn_SpatialClassNLLCriterion_updateOutput_kernel(T *, T *, T *, long *, T *, int, int, int, int, int, long) [with T = float, AccumT = float]: block: [9,0,0], thread: [216,0,0] Assertion `t >= 0 && t < n_classes` failed.
Traceback (most recent call last):
  File "unet2.py", line 242, in <module>
    train(root_train,batch_size,num_epochs)
  File "unet2.py", line 191, in train
    loss.backward()
  File "/storage/node3/yf/anaconda3/lib/python3.6/site-packages/torch/tensor.py", line 107, in backward
    torch.autograd.backward(self, gradient, retain_graph, create_graph)
  File "/storage/node3/yf/anaconda3/lib/python3.6/site-packages/torch/autograd/__init__.py", line 93, in backward
    allow_unreachable=True)  # allow_unreachable flag
RuntimeError: cuDNN error: CUDNN_STATUS_NOT_INITIALIZED

百度了一下,可能是因为驱动的原因,我是cuda8,然后更新了一下现在是cuda10

1
conda install pytorch torchvision cudatoolkit=10.0 -c pytorch

再一次运行unet2模型,还是报一样的错误。然后在网上有看到sudo rm -rf ~/.nv可以解决,试了一下,报错:

1
yf is not in the sudoers file.  This incident will be reported.

发现sudo实在根目录下执行的,所以去掉sudo之后,还是没有解决问题。于是狠心的卸载了pytorch,然后利用pip重新安装了pytorch,然而。。。。。。。。。。。。。。。。这个错误解决了,新的错误出现了。

1
RuntimeError: CUDA error: an illegal memory access was encountered

最后经过师兄的指点发现是因为我的分割图相当于是一个二分类的问题。

1
torch.nn.CrossEntropyLoss()无法用。。。。。。。。。。。。。。。。。哎~~~~基础不牢,地动山摇