# Cross Entropy Loss error on image segmentation

**URL:** <https://discuss.pytorch.org/t/cross-entropy-loss-error-on-image-segmentation/60194>\
**Category:** vision\
**Created:** [November 6, 2019, 4:08pm UTC](https://discuss.pytorch.org/t/cross-entropy-loss-error-on-image-segmentation/60194 "2019-11-06T16:08:42Z")\
**Posts on this page:** 1\
**Showing post:** 12

<div class="post-metadata">

**Author:** ![KFrank](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/k/ecb155/32.png) [@KFrank](https://discuss.pytorch.org/u/KFrank)\
**Post date:** [November 11, 2019, 5:24pm UTC](https://discuss.pytorch.org/t/cross-entropy-loss-error-on-image-segmentation/60194/12 "2019-11-11T17:24:43Z")

</div>

Hello Joe!

> [@joekid](#):
>
> 1. I remake the target as [batch, nClasses, H, W], being nClasses = 5.

No, this is not right. Your `target` (“ground truth”) should be (a  
`LongTensor`) of shape `(batch, H, W)`. For any given sample  
within the batch, the values of the “pixels” in your “H x W” “image”  
should be the integer class labels in `[0, 5)`.

You don’t use multiple “Layers” to specify which class a given  
pixel is in – you just use an integer class label as the value of  
that pixel.

Note, the `input` to `CrossEntropyLoss` is _not_ of the same shape  
as the `target`; the `input` is of shape  
`(batch, nClasses, H, W)`. For any given sample in the batch,  
each pixel in the H x W input “image” has `nClasses` values. These  
are the “logits” (“scores” in -infinity to +infinity) that tell you how likely  
the model thinks a given pixel is to be in each of the `nClasses`  
classes.

> [@](#):
>
> 1. However a get a new error:
> 
> `RuntimeError: 1only batches of spatial targets supported (non-empty 3D tensors) but got targets of size: : [4, 5, 224, 224] ,`
> 
> I use batchsize=5, nClasses=1. The input data is [4,1,224,244] aiming to obtain [4,5,224,244],

This error message looks reasonable in light of what I said above  
(except that it looks like you are actually using `batchsize = 4`,  
not `batchsize = 5`).

Assuming `batchsize = 4`, `nClasses = 5`, `H = 224`, and  
`W = 224`, `CrossEntropyLoss` will be expecting the `input`  
(prediction) you give it to be a `FloatTensor` of shape  
`(4, 5, 244, 244)`, and the `target` (ground truth) to be a  
`LongTensor` of shape (4, 244, 244).

Good luck.

K. Frank

---

_[View the full topic](https://discuss.pytorch.org/t/cross-entropy-loss-error-on-image-segmentation/60194)._
