Error Assertion `cur_target >= 0 && cur_target < n_classes' failed


I am getting a Assertion `cur_target >= 0 && cur_target < n_classes’ failed error while running, 1, cycle_len=1) with a ‘Resnet34’ architecture.

After doing some search it seems number of labels in my training dataset(4251 in my case for Humpback Whale Identification Challenge) is larger than number of output classes in Resnet(which is 1000 I believe) .

Could anyone please suggest how this problem can be approached with fastai library with a pre-trained model.


If you type learn.model you can see what layers and what shapes are in the model. Look at the end of it to see your current output shape.

You can change the end layers of a pre-trained model by using a custom head or setting xtra_fc.

The easier way is to use xtra_fc=[4251] argument for the ConvLearner.pretrained.

You can also use a custom head by using custom_head=normalPytorchModule as an argument in ConvLearner.pretrained.

Thanks, @Hadus for your response. However when I add xtra_fc=[4251]

learn = ConvLearner.pretrained(arch, data, precompute=True, xtra_fc=[4251])

However, when I print learn.model it gives me the following output

(0): BatchNorm1d(1024, eps=1e-05, momentum=0.1, affine=True)
(1): Dropout(p=0.25)
(2): Linear(in_features=1024, out_features=4251, bias=True)
(3): ReLU()
(4): BatchNorm1d(4251, eps=1e-05, momentum=0.1, affine=True)
(5): Dropout(p=0.5)
(6): Linear(in_features=4251, out_features=4250, bias=True)
(7): LogSoftmax()

Is it adding 4251 input nodes in last Linear layer instead of adding 4251 output nodes?

However, custom_head does solve the problem.

Any help. Most of the online forums tells its a pytorch error and do suggest a explanation and solution, but how we implement the same in fastai? like for example check this linkcheck this link

Hi guys,

I am a medicine student and trying to do a bone & background segmentation from ct images. I’m facing the same error.

`cur_target >= 0 && cur_target < n_classes’ failed

I did some research on this (, where people pointed out it could be a mismatch in class sizes. Thus I double checked it in my code, but still receiving that error.

Hi Vaio, have you find the solution? I am facing the same problem in a very similar situation (I use PixelAnnotation to create my own dataset).

no I didn’t made any progress on this topic. I used a dicom viewer, and extracted set bone values to 1 and background to 0 with a Hounsfield threshold.

I am thankful for tips, when are progressing in solving!

Hi vaio,

I am facing the exact same issue right now. Did you find a solution?