[Help] RunTimeError during learn.fit

Hi All,

I am trying to familiarize with the fastai data_block api. Downloaded a kaggle competition Dont-Overfit-ii and tried loading the data with following code.

test = TabularList.from_df(test_df, path=path, cont_names = cont_names)

data = (TabularList.from_df(train_df,path=path, cont_names=cont_names,procs=procs)
            .random_split_by_pct()
            .label_from_df(cols=dep_var)
            .add_test(test)
            .databunch())

The data loaded well and I was able to do a data.show_batch.

learn = tabular_learner(data, layers=[200,100], metrics=accuracy)

learn.fit(1, 1e-2)

The error occurs when I run learn.fit. Please help,

RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 ‘other’

detailed error track :
    > RuntimeError                              Traceback (most recent call last)
    > <ipython-input-37-c6076a6ce3f3> in <module>()
    > ----> 1 learn.fit(1, 1e-2)
    > 
    > /usr/local/lib/python3.6/dist-packages/fastai/basic_train.py in fit(self, epochs, lr, wd, callbacks)
    >     176         callbacks = [cb(self) for cb in self.callback_fns] + listify(callbacks)
    >     177         fit(epochs, self.model, self.loss_func, opt=self.opt, data=self.data, metrics=self.metrics,
    > --> 178             callbacks=self.callbacks+callbacks)
    >     179 
    >     180     def create_opt(self, lr:Floats, wd:Floats=0.)->None:
    > 
    > /usr/local/lib/python3.6/dist-packages/fastai/utils/mem.py in wrapper(*args, **kwargs)
    >     101 
    >     102         try:
    > --> 103             return func(*args, **kwargs)
    >     104         except Exception as e:
    >     105             if ("CUDA out of memory" in str(e) or
    > 
    > /usr/local/lib/python3.6/dist-packages/fastai/basic_train.py in fit(epochs, model, loss_func, opt, data, callbacks, metrics)
    >      93             if not data.empty_val:
    >      94                 val_loss = validate(model, data.valid_dl, loss_func=loss_func,
    > ---> 95                                        cb_handler=cb_handler, pbar=pbar)
    >      96             else: val_loss=None
    >      97             if cb_handler.on_epoch_end(val_loss): break
    > 
    > /usr/local/lib/python3.6/dist-packages/fastai/basic_train.py in validate(model, dl, loss_func, cb_handler, pbar, average, n_batch)
    >      55             if not is_listy(yb): yb = [yb]
    >      56             nums.append(yb[0].shape[0])
    > ---> 57             if cb_handler and cb_handler.on_batch_end(val_losses[-1]): break
    >      58             if n_batch and (len(nums)>=n_batch): break
    >      59         nums = np.array(nums, dtype=np.float32)
    > 
    > /usr/local/lib/python3.6/dist-packages/fastai/callback.py in on_batch_end(self, loss)
    >     257         "Handle end of processing one batch with `loss`."
    >     258         self.state_dict['last_loss'] = loss
    > --> 259         stop = np.any(self('batch_end', not self.state_dict['train']))
    >     260         if self.state_dict['train']:
    >     261             self.state_dict['iteration'] += 1
    > 
    > /usr/local/lib/python3.6/dist-packages/fastai/callback.py in __call__(self, cb_name, call_mets, **kwargs)
    >     198     def __call__(self, cb_name, call_mets=True, **kwargs)->None:
    >     199         "Call through to all of the `CallbakHandler` functions."
    > --> 200         if call_mets: [getattr(met, f'on_{cb_name}')(**self.state_dict, **kwargs) for met in self.metrics]
    >     201         return [getattr(cb, f'on_{cb_name}')(**self.state_dict, **kwargs) for cb in self.callbacks]
    >     202 
    > 
    > /usr/local/lib/python3.6/dist-packages/fastai/callback.py in <listcomp>(.0)
    >     198     def __call__(self, cb_name, call_mets=True, **kwargs)->None:
    >     199         "Call through to all of the `CallbakHandler` functions."
    > --> 200         if call_mets: [getattr(met, f'on_{cb_name}')(**self.state_dict, **kwargs) for met in self.metrics]
    >     201         return [getattr(cb, f'on_{cb_name}')(**self.state_dict, **kwargs) for cb in self.callbacks]
    >     202 
    > 
    > /usr/local/lib/python3.6/dist-packages/fastai/callback.py in on_batch_end(self, last_output, last_target, **kwargs)
    >     292         if not is_listy(last_target): last_target=[last_target]
    >     293         self.count += last_target[0].size(0)
    > --> 294         self.val += last_target[0].size(0) * self.func(last_output, *last_target).detach().cpu()
    >     295 
    >     296     def on_epoch_end(self, **kwargs):
    > 
    > /usr/local/lib/python3.6/dist-packages/fastai/metrics.py in accuracy(input, targs)
    >      27     input = input.argmax(dim=-1).view(n,-1)
    >      28     targs = targs.view(n,-1)
    > ---> 29     return (input==targs).float().mean()
    >      30 
    >      31 def accuracy_thresh(y_pred:Tensor, y_true:Tensor, thresh:float=0.5, sigmoid:bool=True)->Rank0Tensor:
    > 
    > RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 'other'
1 Like

Realized my target variable was float 0 and 1.0 instead of integer 0 and 1.

added the following code to convert the target variable type fixed this.
train_df.target=train_df.target.astype(int)

If someone is still interested, I have the same error message but it is due to an error creating the ImageList

I’m having this issue. Where exactly did you correct this?

Code that throws the error:

learn = tabular_learner(dls, layers=[200,100], loss_func=mse, metrics=accuracy)

learn.fit(epoch, learning_rate)