# Multiclass Segmentation

**URL:** <https://discuss.pytorch.org/t/multiclass-segmentation/54065>\
**Category:** Uncategorized\
**Created:** [August 22, 2019, 2:57pm UTC](https://discuss.pytorch.org/t/multiclass-segmentation/54065 "2019-08-22T14:57:22Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![ru6928](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/r/3be4f8/32.png) [@ru6928](https://discuss.pytorch.org/u/ru6928)\
**Post date:** [August 22, 2019, 2:57pm UTC](https://discuss.pytorch.org/t/multiclass-segmentation/54065/1 "2019-08-22T14:57:22Z")

</div>

Hi, is there an example for creating a custom dataset and training for multiclass segmentation using U-Net? I find many examples for binary segmentation but yet to find something for multiclass segmentation. Thank you!

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [August 22, 2019, 4:47pm UTC](https://discuss.pytorch.org/t/multiclass-segmentation/54065/2 "2019-08-22T16:47:15Z")

</div>

I assume you have already found suitable code snippets for a binary segmentation use case?  
If so, you could use it as a base line and make a few changes for a multi class segmentation use case:

- use `nn.CrossEntropyLoss` as your criterion
- your model should output a tensor with the shape `[batch_size, nb_classes, height ,width]`
- the `target` should be a `LongTensor` with the shape `[batch_size, height, width]` and contain the class indices for each pixel location in the range `[0, nb_classes-1]`

Depending on the format of your segmentation mask images, you might need to create a mapping e.g. between color codes and the corresponding class indices.

Let us know, if and where you get stuck.

---

<div class="post-metadata">

**Author:** ![ru6928](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/r/3be4f8/32.png) [@ru6928](https://discuss.pytorch.org/u/ru6928)\
**Post date:** [August 22, 2019, 5:28pm UTC](https://discuss.pytorch.org/t/multiclass-segmentation/54065/3 "2019-08-22T17:28:06Z")

</div>

Thank you very much for the reply. I have 2 follow up questions -  
1 - in binary, the output of the U-net model will is a softmax(). Will it be the same for multi-class?  
2 - my target has 3 classes. So, I should have 0 for background and 1,2,3 for the three classes at each pixel location, right?

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [August 22, 2019, 5:31pm UTC](https://discuss.pytorch.org/t/multiclass-segmentation/54065/4 "2019-08-22T17:31:37Z")

</div>

1. If you are using `nn.BCELoss`, the output should use `torch.sigmoid` as the activation function. Alternatively, you won’t use any activation function and pass raw logits to `nn.BCEWithLogitsLoss`. If you use `nn.CrossEntropyLoss` for the multi-class segmentation, you should also pass the raw logits without using any activation function.

2. Yes, but then you should deal with 4 classes (background + 3 classes), so the output of your model should be `[batch_size, 4, h, w]`.

---

<div class="post-metadata">

**Author:** ![Rishav\_Sapahia](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/r/51bf81/32.png) [@Rishav\_Sapahia](https://discuss.pytorch.org/u/Rishav_Sapahia)\
**Post date:** [August 22, 2019, 6:51pm UTC](https://discuss.pytorch.org/t/multiclass-segmentation/54065/5 "2019-08-22T18:51:39Z")

</div>

I have a follow up question on this-  
1)Do we need to apply any normalisation on the masks?

Following is my custom data loader for image segmentation-

```auto
class DataLoaderSegmentation(data.Dataset):
    def __init__ (self,folder_path,transform = None):
        super(DataLoaderSegmentation, self). __init__ ()
        self.img_files = glob.glob(os.path.join(folder_path,'images','*.tif'))
        self.mask_files = glob.glob(os.path.join(folder_path,'mask','*.bmp'))
        self.transform = transform
    def __getitem__ (self, index):
        img_path = self.img_files[index]
        mask_path = self.mask_files[index]
        data = Image.open(img_path)
        label = Image.open(mask_path)
        if self.transform:
            data = self.transform(data)
        label = np.array(label)
        return data, torch.from_numpy(label).long()
    
    def __len__ (self):
        return len(self.img_files)`Preformatted text`

```

Also when I don’t use `transform.ToTensor` normalisation but rather use `torch.from_numpy(label).long()`, the shape of target comes out to be `Batch_size,height,width,num_channels`  
2)Why the difference and how to solve this problem?  
3)Also, I couldn’t understand this line much `Depending on the format of your segmentation mask images, you might need to create a mapping e.g. between color codes and the corresponding class indices.`

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [August 22, 2019, 10:25pm UTC](https://discuss.pytorch.org/t/multiclass-segmentation/54065/6 "2019-08-22T22:25:45Z")

</div>

Most likely you should not apply any normalization on your segmentation masks, as this will distort the class indices.  
Could you print the shape of `label` before passing it to `torch.from_numpy`?  
I would assume the channel in in dim0 or your images don’t have the channel dimension, if you are loading them with `PIL`.

Have a look at [this post](https://discuss.pytorch.org/t/error-in-python-s-multiprocessing-library/31355/6) where I’ve explained the mapping a bit better.  
Basically your targets should contain class indices in `[0, nb_classes]`.  
However, sometimes your segmentation images use a color code for certain classes, e.g. red could be a car and blue could be a tree. Using a mapping, you would have to transform these color codes to class indices, e.g. red-\>0, blue-\>1, …

PS: If you are resizing the mask images, make sure to use nearest neighbor interpolation, as other interpolation techniques might distort the labels/colors.

---

<div class="post-metadata">

**Author:** ![Rishav\_Sapahia](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/r/51bf81/32.png) [@Rishav\_Sapahia](https://discuss.pytorch.org/u/Rishav_Sapahia)\
**Post date:** [August 23, 2019, 2:41pm UTC](https://discuss.pytorch.org/t/multiclass-segmentation/54065/7 "2019-08-23T14:41:10Z")

</div>

Yes, when I print the shape of image after converting it into numpy array, even reading from both `cv2` and `PIL`, the output shape is `3*512*512` which I corrected using `np.transpose(imgs,(2,0,1))`.

I got your point regarding the mapping but how to define the mapping for RGB images, my masks have 4 classes- Blue,Red,Green and black background.

I am not resizing the mask images but I am Random Cropping the original image to a smaller size and my final output segmented image is same size as of cropped input image.Is it the right way to do it, are there any performance issues with it?

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [August 23, 2019, 4:31pm UTC](https://discuss.pytorch.org/t/multiclass-segmentation/54065/8 "2019-08-23T16:31:25Z")

</div>

Have a look at [this post](https://discuss.pytorch.org/t/training-semantic-segmentation/49275/4) to see, how to create a custom mapping.

`RandomCrop` should work in the default setup without padding. However, you should make sure to use the same “random” locations for both, your input and target as shown [here](https://discuss.pytorch.org/t/torchvision-transfors-how-to-perform-identical-transform-on-both-image-and-target/10606/7).

---

<div class="post-metadata">

**Author:** ![Rishav\_Sapahia](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/r/51bf81/32.png) [@Rishav\_Sapahia](https://discuss.pytorch.org/u/Rishav_Sapahia)\
**Post date:** [August 27, 2019, 10:47pm UTC](https://discuss.pytorch.org/t/multiclass-segmentation/54065/9 "2019-08-27T22:47:07Z")

</div>

okay, I followed the post and implemented the following dataloader class keeping in mind the same random locations for both input and target.  
First, I want to show the required transformation by me which I have applied in a normal way if I don’t need to apply them simultaneously-

```auto
data_transforms = transforms.Compose([transforms.RandomCrop((512,512)),
                                 transforms.Lambda(gaussian_blur),
                                 transforms.Lambda(elastic_transform),
                                 transforms.RandomRotation([+90,+180]),
                                 transforms.RandomRotation([+180,+270]),
                                 transforms.RandomHorizontalFlip(),
                                 transforms.ToTensor(),
                                 transforms.Normalize(mean=train_mean, std=train_std)
                               ])

```

Now, the thing is I can apply `RandomCrop, Random Rotation, ToTensor` in the class but I have no idea how to apply `gaussian_blur,elastic_transform and Normalization with custom mean`  
Also, below is my dataloader class

```auto
class DataLoaderSegmentation(data.Dataset):
    def __init__ (self,folder_path):
        super(DataLoaderSegmentation, self). __init__ ()
        self.img_files = glob.glob(os.path.join(folder_path,'images','*.tif'))
        self.mask_files = glob.glob(os.path.join(folder_path,'mask','*.bmp'))
  
    def mask_to_class(self,mask):
        target = torch.from_numpy(mask)
        h,w = target.shape[0],target.shape[1]
        masks = torch.empty(h, w, dtype=torch.long)
        colors = torch.unique(target.view(-1,target.size(2)),dim=0).numpy()
        target = target.permute(2, 0, 1).contiguous()
        mapping = {tuple(c): t for c, t in zip(colors.tolist(), range(len(colors)))}
        for k in mapping:
            idx = (target==torch.tensor(k, dtype=torch.uint8).unsqueeze(1).unsqueeze(2))
            validx = (idx.sum(0) == 3) 
            masks[validx] = torch.tensor(mapping[k], dtype=torch.long)
        return masks
    
    def transform(self,image,mask):
        i, j, h, w = transforms.RandomCrop.get_params(
        image, output_size=(512, 512))
        image = TF.crop(image, i, j, h, w)
        mask = TF.crop(mask, i, j, h, w)

        # Random horizontal flipping
        if random.random() > 0.5:
            image = TF.hflip(image)
            mask = TF.hflip(mask)
        
        image = TF.rotate(image,90)
        mask = TF.rotate(mask,90)
        image = TF.rotate(image,180)
        mask = TF.rotate(mask,180)
        image = TF.rotate(image,270)
        mask = TF.rotate(mask,270)

        # Transform to tensor
        image = TF.to_tensor(image)
        mask = TF.to_tensor(mask)
        return image, mask
    
    def __getitem__ (self, index):
        img_path = self.img_files[index]
        mask_path = self.mask_files[index]
        data = Image.open(img_path)
        label = Image.open(mask_path)
        data,label = self.transform(data,label)
        label = np.array(label)
        mask = self.mask_to_class(label)
        return data,mask
           
    def __len__ (self):
        return len(self.img_files)

```

I am obtaining the following error -

```auto
RuntimeError: Assertion `input0 == target0 && input2 == target1 && input3 == target2' failed. size mismatch (got input: 5x4x504x504, target: 5x584x565) at ../aten/src/THNN/generic/SpatialClassNLLCriterion.c:59

```

Because size of my label is now `batch_size*height*width`, so does this implies I have to do certain change in my network too or is someplace else I am screwing up?

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [August 28, 2019, 10:21am UTC](https://discuss.pytorch.org/t/multiclass-segmentation/54065/10 "2019-08-28T10:21:03Z")

</div>

The number of dimensions look alright. However the spatial size is different.  
While your data is `[504 x 504]`, your target is `[584 x 565]`, which will throw this error.

Also, be careful about using `TF.to_tensor` on your mask, as this might normalize the class indices into float values in the range `[0, 1]`.

---

<div class="post-metadata">

**Author:** ![Rishav\_Sapahia](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/r/51bf81/32.png) [@Rishav\_Sapahia](https://discuss.pytorch.org/u/Rishav_Sapahia)\
**Post date:** [August 28, 2019, 10:06pm UTC](https://discuss.pytorch.org/t/multiclass-segmentation/54065/11 "2019-08-28T22:06:40Z")

</div>

Thanks a lot, there was a problem in the architecture which I resolved.  
Yes, I removed `TF.to_tensor` on the mask though yet to figure out how to do selective transformations on it.  
Although I am encountering the following error on running the current network-

```auto
RuntimeError: Assertion `cur_target >= 0 && cur_target < n_classes' failed. at/aten/src/THNN/generic/SpatialClassNLLCriterion.c:109

```

Now, I am not able to figure out where I am doing wrong?

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [August 29, 2019, 9:59pm UTC](https://discuss.pytorch.org/t/multiclass-segmentation/54065/12 "2019-08-29T21:59:42Z")

</div>

Make sure the target has the shape `[N, H, W]` and contains class indices in the range `[0, nb_classes-1]`, while your output should have the shape `[N, nb_classes, H, W]`.  
Apparently some target tensor contains values outside of this range.  
You could use a print statement while iterating your `DataLoader` to track down the problematic batch.

---

<div class="post-metadata">

**Author:** ![Adithia\_Jo](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/adithia_jo/32/23049_2.png) [@Adithia\_Jo](https://discuss.pytorch.org/u/Adithia_Jo)\
**Post date:** [April 20, 2020, 3:40pm UTC](https://discuss.pytorch.org/t/multiclass-segmentation/54065/13 "2020-04-20T15:40:04Z")

</div>

from **future** import print\_function  
from keras.preprocessing.image import ImageDataGenerator  
import numpy as np  
import os  
import glob  
import [skimage.io](http://skimage.io/) as io  
import skimage.transform as trans

def adjustData(img,mask,flag\_multi\_class,num\_class):  
if(flag\_multi\_class):  
img = img / 255  
mask = mask[:,:,:,0] if(len(mask.shape) == 4) else mask[:,:,0]  
new\_mask = np.zeros(mask.shape + (num\_class,))  
for i in range(num\_class):  
#for one pixel in the image, find the class in mask and convert it into one-hot vector  
#index = np.where(mask == i)  
#index\_mask = (index[0],index[1],index[2],np.zeros(len(index[0]),dtype = np.int64) + i) if (len(mask.shape) == 4) else (index[0],index[1],np.zeros(len(index[0]),dtype = np.int64) + i)  
#new\_mask[index\_mask] = 1  
new\_mask[mask == i,i] = 1  
new\_mask = np.reshape(new\_mask,(new\_mask.shape[0],new\_mask.shape[1]\*new\_mask.shape[2],new\_mask.shape[3])) if flag\_multi\_class else np.reshape(new\_mask,(new\_mask.shape[0]\*new\_mask.shape[1],new\_mask.shape[2]))  
mask = new\_mask  
elif(np.max(img) \> 1):  
img = img / 255  
mask = mask /255  
mask[mask \> 0.5] = 1  
mask[mask \<= 0.5] = 0  
return (img,mask)

def trainGenerator(batch\_size,train\_path,image\_folder,mask\_folder,aug\_dict,image\_color\_mode = “grayscale”,  
mask\_color\_mode = “grayscale”,image\_save\_prefix = “image”,mask\_save\_prefix = “mask”,  
flag\_multi\_class = False,num\_class = 2,save\_to\_dir = None,target\_size = (256,256),seed = 1):  
‘’’  
can generate image and mask at the same time  
use the same seed for image\_datagen and mask\_datagen to ensure the transformation for image and mask is the same  
if you want to visualize the results of generator, set save\_to\_dir = “your path”  
‘’’  
image\_datagen = ImageDataGenerator(\*\*aug\_dict)  
mask\_datagen = ImageDataGenerator(\*\*aug\_dict)  
image\_generator = image\_datagen.flow\_from\_directory(  
train\_path,  
classes = [image\_folder],  
class\_mode = None,  
color\_mode = image\_color\_mode,  
target\_size = target\_size,  
batch\_size = batch\_size,  
save\_to\_dir = save\_to\_dir,  
save\_prefix = image\_save\_prefix,  
seed = seed)  
mask\_generator = mask\_datagen.flow\_from\_directory(  
train\_path,  
classes = [mask\_folder],  
class\_mode = None,  
color\_mode = mask\_color\_mode,  
target\_size = target\_size,  
batch\_size = batch\_size,  
save\_to\_dir = save\_to\_dir,  
save\_prefix = mask\_save\_prefix,  
seed = seed)  
train\_generator = zip(image\_generator, mask\_generator)  
for (img,mask) in train\_generator:  
img,mask = adjustData(img,mask,flag\_multi\_class,num\_class)  
yield (img,mask)

def valGenerator(batch\_size,train\_path,image\_folder,mask\_folder,image\_color\_mode = “grayscale”,  
mask\_color\_mode = “grayscale”,image\_save\_prefix = “image”,mask\_save\_prefix = “mask”,  
flag\_multi\_class = False,num\_class = 2,save\_to\_dir = None,target\_size = (256,256),seed = 1):  
‘’’  
can generate image and mask at the same time  
use the same seed for image\_datagen and mask\_datagen to ensure the transformation for image and mask is the same  
if you want to visualize the results of generator, set save\_to\_dir = “your path”  
‘’’  
image\_datagen = ImageDataGenerator()  
mask\_datagen = ImageDataGenerator()  
image\_generator = image\_datagen.flow\_from\_directory(  
train\_path,  
classes = [image\_folder],  
class\_mode = None,  
color\_mode = image\_color\_mode,  
target\_size = target\_size,  
batch\_size = batch\_size,  
save\_to\_dir = save\_to\_dir,  
save\_prefix = image\_save\_prefix,  
seed = seed)  
mask\_generator = mask\_datagen.flow\_from\_directory(  
train\_path,  
classes = [mask\_folder],  
class\_mode = None,  
color\_mode = mask\_color\_mode,  
target\_size = target\_size,  
batch\_size = batch\_size,  
save\_to\_dir = save\_to\_dir,  
save\_prefix = mask\_save\_prefix,  
seed = seed)  
train\_generator = zip(image\_generator, mask\_generator)  
for (img,mask) in train\_generator:  
img,mask = adjustData(img,mask,flag\_multi\_class,num\_class)  
yield (img,mask)

def testGenerator(test\_path,num\_image = 18,target\_size = (256,256),flag\_multi\_class = False,as\_gray = True):  
for i in test\_path:  
img = io.imread(i, as\_gray = as\_gray)  
print(i)

# img = img / 255

```auto
    img = trans.resize(img,target_size)
    img = np.reshape(img,img.shape+(1,)) if (not flag_multi_class) else img
    img = np.reshape(img,(1,)+img.shape)
    yield img

```

def testGenerator2(batch\_size,test\_path,target\_size = (256,256), image\_color\_mode = “grayscale”, num\_class = 2,flag\_multi\_class = False,as\_gray = True):  
image\_datagen = ImageDataGenerator()  
image\_generator = image\_datagen.flow\_from\_directory(  
test\_path,  
class\_mode = None,  
color\_mode = image\_color\_mode,  
target\_size = target\_size,  
batch\_size = batch\_size  
)  
return image\_generator

def geneTrainNpy(image\_path,mask\_path,flag\_multi\_class = False,num\_class = 2,image\_prefix = “image”,mask\_prefix = “mask”,image\_as\_gray = True,mask\_as\_gray = True):  
image\_name\_arr = glob.glob(os.path.join(image\_path,"%s\*.png"%image\_prefix))  
image\_arr = []  
mask\_arr = []  
for index,item in enumerate(image\_name\_arr):  
img = io.imread(item,as\_gray = image\_as\_gray)  
img = np.reshape(img,img.shape + (1,)) if image\_as\_gray else img  
mask = io.imread(item.replace(image\_path,mask\_path).replace(image\_prefix,mask\_prefix),as\_gray = mask\_as\_gray)  
mask = np.reshape(mask,mask.shape + (1,)) if mask\_as\_gray else mask  
img,mask = adjustData(img,mask,flag\_multi\_class,num\_class)  
image\_arr.append(img)  
mask\_arr.append(mask)  
image\_arr = np.array(image\_arr)  
mask\_arr = np.array(mask\_arr)  
return image\_arr,mask\_arr

def labelVisualize(num\_class,color\_dict,img):  
img = img[:,:,0] if len(img.shape) == 3 else img  
img\_out = np.zeros(img.shape + (3,))  
for i in range(num\_class):  
img\_out[img == i,:] = color\_dict[i]  
return img\_out

def labelVisualizeBinary(img):  
img[img \> 0.5] = 1  
img[img\<= 0.5] = 0  
return img

def saveResult(save\_path,results\_filename,npyfile,flag\_multi\_class = False,num\_class = 2):  
print(results\_filename[0])  
for i,item in enumerate(npyfile):  
img = labelVisualize(num\_class,COLOR\_DICT,item) if flag\_multi\_class else item[:,:,0]  
print(i)  
io.imsave(os.path.join(save\_path,results\_filename[i]),img)

#### my problem

this is my data code , i have problem how to change it to multiclass segmentation,  
i divided codes with 3 part , 1 for data(to transform (num classes), 1 for train(like epoch,path\_to\_train,etc) , and 1 for model (unet)

in my model i was change the loss function to sparse\_categorical\_crossentropy, and the last layer to softmax,i know my problem in the data codes (how to transform it multiclass (num classes), i has 3 output (black,white, red) that mean my num\_classes = 3), but i dont know how to change it? i just change the num\_classes but nothing happend , maybe you can solve my problem thank you 🙂 (codes up here) thank you

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [April 20, 2020, 4:35pm UTC](https://discuss.pytorch.org/t/multiclass-segmentation/54065/14 "2020-04-20T16:35:42Z")

</div>

It seems you are using Keras not PyTorch, so I think you will get a better answer on StackOverflow.  
I’m not familiar enough with the data loading in Keras. 😕

---

<div class="post-metadata">

**Author:** ![Adithia\_Jo](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/adithia_jo/32/23049_2.png) [@Adithia\_Jo](https://discuss.pytorch.org/u/Adithia_Jo)\
**Post date:** [April 20, 2020, 4:41pm UTC](https://discuss.pytorch.org/t/multiclass-segmentation/54065/15 "2020-04-20T16:41:02Z")

</div>

okay , sir do you have complete codes multiclass segmentation ? (data,model,train) ? can you give it to me? thank you sir 🙂

---

<div class="post-metadata">

**Author:** ![Arun\_Mohan](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/arun_mohan/32/23114_2.png) [@Arun\_Mohan](https://discuss.pytorch.org/u/Arun_Mohan)\
**Post date:** [May 1, 2020, 4:51am UTC](https://discuss.pytorch.org/t/multiclass-segmentation/54065/16 "2020-05-01T04:51:58Z")

</div>

Could you please explain how there are 4 channels(classes) in output. Because if we have 3 channels in output and if 3 channels are empty(that means no segmentation).We can automatically consider this case as background.right?So it would work with 3 channels.ie, output can be [batch\_size, 3, h, w] for 3 classes + BG class. right? please correct me if iam wrong.

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [May 1, 2020, 5:36am UTC](https://discuss.pytorch.org/t/multiclass-segmentation/54065/17 "2020-05-01T05:36:04Z")

</div>

This wouldn’t work for a multi-class segmentation with `nn.CrossEntropyLoss` or `nn.NLLLoss`, since the target has to contain a class index.  
With three classes the class indices would be `[0, 1, 2]` and that for each pixel one of these classes would be active.

If you consider your use case a multi-label segmentation, you could use `nn.BCEWithLogitsLoss`, which would allow you to define zero, one, or more active classes for each pixel.  
This approach would work for 3 explicit channels, as no active class could be considered the “background class”. However, since each pixel could also have all classes set to active, this would be a multi-label segmentation.

---

<div class="post-metadata">

**Author:** ![sky](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/s/f4b2a3/32.png) [@sky](https://discuss.pytorch.org/u/sky)\
**Post date:** [November 8, 2020, 2:36am UTC](https://discuss.pytorch.org/t/multiclass-segmentation/54065/20 "2020-11-08T02:36:12Z")

</div>

Thanks you. But I’m not understand when we deal with 4 classes (background + 3 classes),the output of model should be `[batch_size, 4, h, w]`，I what to know 1) if the target should use the onehot encode and 2) what the target should like ? ([batch\_size, height, width] using onehot encode or no use)

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [November 9, 2020, 5:54am UTC](https://discuss.pytorch.org/t/multiclass-segmentation/54065/21 "2020-11-09T05:54:04Z")

</div>

If you are using `nn.CrossEntropyLoss` and your model outputs the mentioned shape, your target should have the shape `[batch_size, height, width]` and contain class indices in the range `[0, 3]`, i.e. it should not be one-hot encoded.

---

<div class="post-metadata">

**Author:** ![Julien\_Guegan](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/julien_guegan/32/29247_2.png) [@Julien\_Guegan](https://discuss.pytorch.org/u/Julien_Guegan)\
**Post date:** [November 23, 2020, 3:41pm UTC](https://discuss.pytorch.org/t/multiclass-segmentation/54065/22 "2020-11-23T15:41:14Z")

</div>

What if I use the DiceLoss ? Should it be one-hot encoded in this case ?

[Next page](https://discuss.pytorch.org/t/multiclass-segmentation/54065.md?page=2)
