Problems with model prediction (incorrect output dimensions)

I was trying out an image segmentation task. While trying to train the model, I was getting the error:

RuntimeError: Assertion `cur_target >= 0 && cur_target < n_classes' failed.  at /pytorch/aten/src/THNN/generic/ClassNLLCriterion.c:92

I read some threads here and in an attempt to narrow down the problem, I tried to make a prediction and I noticed a problem. The following is by DataBunch:

ImageDataBunch;

Train: LabelList (116 items)
x: SegmentationItemList
Image (3, 128, 128),Image (3, 128, 128),Image (3, 128, 128),Image (3, 128, 128),Image (3, 128, 128)
y: SegmentationLabelList
ImageSegment (1, 128, 128),ImageSegment (1, 128, 128),ImageSegment (1, 128, 128),ImageSegment (1, 128, 128),ImageSegment (1, 128, 128)
Path: /content/drive/My Drive/AutoBound Data/cleaned/originalImages;

Valid: LabelList (29 items)
x: SegmentationItemList
Image (3, 128, 128),Image (3, 128, 128),Image (3, 128, 128),Image (3, 128, 128),Image (3, 128, 128)
y: SegmentationLabelList
ImageSegment (1, 128, 128),ImageSegment (1, 128, 128),ImageSegment (1, 128, 128),ImageSegment (1, 128, 128),ImageSegment (1, 128, 128)
Path: /content/drive/My Drive/AutoBound Data/cleaned/originalImages;

Test: None

When I make a prediction on a batch (9 items per batch), I get an output of the following size:

torch.Size([9, 2, 128, 128])

The segmented image in my data bunch had the dimensions [1,128,128], but the output image has the above dimensions. I believe this was causing the problem. How do I fix this?

How many classes you have for your segmentation task?

Just two classes. I’m trying to segment satellite images into areas with and without images.
This is a sample segmented image

and this is a sample original image

The output dimension [9, 2, 128, 128] is giving you the probabilities. So you need to take the argmax along the second dimension. The 2 here is prob for every class. So if you had 10 classes this value would have been 10.

Okay. So, the training should happen properly. But I keep getting that error I mentioned before:

While trying to train the model, I was getting the error:

RuntimeError: Assertion `cur_target >= 0 && cur_target < n_classes' failed.  at >/pytorch/aten/src/THNN/generic/ClassNLLCriterion.c:92

Some threads mentioned they might be because of index out of bounds.

The problem is probably due to wrong dimensions in your architecture. Can you check your final linear layers for correct dimensions?

Hi Vishal, have you solved this problem? Because I am having the same error :slight_smile:

RuntimeError: Assertion `cur_target >= 0 && cur_target < n_classes’ failed. at /pytorch/aten/src/THNN/generic/ClassNLLCriterion.c:92