Tabular Learner Type Error

Hi everyone!

I’m new in Fastai, and I got this error when I try to use fastai tabular:

Expected object of scalar type Long but got scalar type Char for argument #2 ‘target’ in call to _thnn_nll_loss_forward

My code :

y_names = 'species'
cont_names = ['bill_length_mm', 'bill_depth_mm', 'flipper_length_mm', 'body_mass_g']
procs = [Normalize]
trainloader = TabularDataLoaders.from_df(datatrain, procs = procs,
                            cont_names = cont_names,
                            y_names = y_names)
learn = tabular_learner(trainloader, layers=[20], metrics=accuracy, loss_func=nn.CrossEntropyLoss()), 0.1)

datatrain is a dataframe that I read using pandas read_csv. It looks like this:

The error is only happen when I use PyTorch nn.CrossEntropyLoss() but I don’t know why?

I’m not sure but I think the problem is

loss_func can be any loss function you like. It needs to be one of fastai’s if you want to use Learn.predict or Learn.get_preds, or you will have to implement special methods (see more details after the BaseLoss documentation).


But I’m still not sure as I read from this tutorial:, he combined PyTorch and FastAI and then use nn.CrossEntropyLoss() as a loss function.

And also the error is appear when I run fit() not predict or get_preds as stated above

try passing y_block = CategoryBlock in your TabularDataLoaders.from_df()?

and you need not pass loss_func argument explicitly if it is CrossEntropyLoss that you want as your loss, as it automatically does it for you based on your y_block. (try printing learn.loss_func after defining learner)

Unfortunately it still doesn’t work :frowning:

That’s true that we don’t need to define the CrossEntropyLoss using nn.CrossEntropyLoss, in this case I just want to try it, as I thought it should work :thinking: