TypeError with `tabular_learner` for classification

I am trying to use the tabular_learner for classification with the Iris dataset. I am running into the following TypeError:

TypeError                                 Traceback (most recent call last)
Cell In[16], line 1
----> 1 learn.fit_one_cycle(1)

File /home/sp/torch/.venv/lib/python3.8/site-packages/fastai/callback/schedule.py:119, in fit_one_cycle(self, n_epoch, lr_max, div, div_final, pct_start, wd, moms, cbs, reset_opt, start_epoch)
    116 lr_max = np.array([h['lr'] for h in self.opt.hypers])
    117 scheds = {'lr': combined_cos(pct_start, lr_max/div, lr_max, lr_max/div_final),
    118           'mom': combined_cos(pct_start, *(self.moms if moms is None else moms))}
--> 119 self.fit(n_epoch, cbs=ParamScheduler(scheds)+L(cbs), reset_opt=reset_opt, wd=wd, start_epoch=start_epoch)

File /home/sp/torch/.venv/lib/python3.8/site-packages/fastai/learner.py:264, in Learner.fit(self, n_epoch, lr, wd, cbs, reset_opt, start_epoch)
    262 self.opt.set_hypers(lr=self.lr if lr is None else lr)
    263 self.n_epoch = n_epoch
--> 264 self._with_events(self._do_fit, 'fit', CancelFitException, self._end_cleanup)

File /home/sp/torch/.venv/lib/python3.8/site-packages/fastai/learner.py:199, in Learner._with_events(self, f, event_type, ex, final)
    198 def _with_events(self, f, event_type, ex, final=noop):
--> 199     try: self(f'before_{event_type}');  f()
    200     except ex: self(f'after_cancel_{event_type}')
    201     self(f'after_{event_type}');  final()

File /home/sp/torch/.venv/lib/python3.8/site-packages/fastai/learner.py:253, in Learner._do_fit(self)
    251 for epoch in range(self.n_epoch):
    252     self.epoch=epoch
--> 253     self._with_events(self._do_epoch, 'epoch', CancelEpochException)

File /home/sp/torch/.venv/lib/python3.8/site-packages/fastai/learner.py:199, in Learner._with_events(self, f, event_type, ex, final)
    198 def _with_events(self, f, event_type, ex, final=noop):
--> 199     try: self(f'before_{event_type}');  f()
    200     except ex: self(f'after_cancel_{event_type}')
    201     self(f'after_{event_type}');  final()

File /home/sp/torch/.venv/lib/python3.8/site-packages/fastai/learner.py:248, in Learner._do_epoch(self)
    246 def _do_epoch(self):
    247     self._do_epoch_train()
--> 248     self._do_epoch_validate()

File /home/sp/torch/.venv/lib/python3.8/site-packages/fastai/learner.py:244, in Learner._do_epoch_validate(self, ds_idx, dl)
    242 if dl is None: dl = self.dls[ds_idx]
    243 self.dl = dl
--> 244 with torch.no_grad(): self._with_events(self.all_batches, 'validate', CancelValidException)

File /home/sp/torch/.venv/lib/python3.8/site-packages/fastai/learner.py:199, in Learner._with_events(self, f, event_type, ex, final)
    198 def _with_events(self, f, event_type, ex, final=noop):
--> 199     try: self(f'before_{event_type}');  f()
    200     except ex: self(f'after_cancel_{event_type}')
    201     self(f'after_{event_type}');  final()

File /home/sp/torch/.venv/lib/python3.8/site-packages/fastai/learner.py:205, in Learner.all_batches(self)
    203 def all_batches(self):
    204     self.n_iter = len(self.dl)
--> 205     for o in enumerate(self.dl): self.one_batch(*o)

File /home/sp/torch/.venv/lib/python3.8/site-packages/fastai/learner.py:235, in Learner.one_batch(self, i, b)
    233 b = self._set_device(b)
    234 self._split(b)
--> 235 self._with_events(self._do_one_batch, 'batch', CancelBatchException)

File /home/sp/torch/.venv/lib/python3.8/site-packages/fastai/learner.py:201, in Learner._with_events(self, f, event_type, ex, final)
    199 try: self(f'before_{event_type}');  f()
    200 except ex: self(f'after_cancel_{event_type}')
--> 201 self(f'after_{event_type}');  final()

File /home/sp/torch/.venv/lib/python3.8/site-packages/fastai/learner.py:172, in Learner.__call__(self, event_name)
--> 172 def __call__(self, event_name): L(event_name).map(self._call_one)

File /home/sp/torch/.venv/lib/python3.8/site-packages/fastcore/foundation.py:156, in L.map(self, f, *args, **kwargs)
--> 156 def map(self, f, *args, **kwargs): return self._new(map_ex(self, f, *args, gen=False, **kwargs))

File /home/sp/torch/.venv/lib/python3.8/site-packages/fastcore/basics.py:840, in map_ex(iterable, f, gen, *args, **kwargs)
    838 res = map(g, iterable)
    839 if gen: return res
--> 840 return list(res)

File /home/sp/torch/.venv/lib/python3.8/site-packages/fastcore/basics.py:825, in bind.__call__(self, *args, **kwargs)
    823     if isinstance(v,_Arg): kwargs[k] = args.pop(v.i)
    824 fargs = [args[x.i] if isinstance(x, _Arg) else x for x in self.pargs] + args[self.maxi+1:]
--> 825 return self.func(*fargs, **kwargs)

File /home/sp/torch/.venv/lib/python3.8/site-packages/fastai/learner.py:176, in Learner._call_one(self, event_name)
    174 def _call_one(self, event_name):
    175     if not hasattr(event, event_name): raise Exception(f'missing {event_name}')
--> 176     for cb in self.cbs.sorted('order'): cb(event_name)

File /home/sp/torch/.venv/lib/python3.8/site-packages/fastai/callback/core.py:62, in Callback.__call__(self, event_name)
     60     try: res = getcallable(self, event_name)()
     61     except (CancelBatchException, CancelBackwardException, CancelEpochException, CancelFitException, CancelStepException, CancelTrainException, CancelValidException): raise
---> 62     except Exception as e: raise modify_exception(e, f'Exception occured in `{self.__class__.__name__}` when calling event `{event_name}`:\n\t{e.args[0]}', replace=True)
     63 if event_name=='after_fit': self.run=True #Reset self.run to True at each end of fit
     64 return res

File /home/sp/torch/.venv/lib/python3.8/site-packages/fastai/callback/core.py:60, in Callback.__call__(self, event_name)
     58 res = None
     59 if self.run and _run: 
---> 60     try: res = getcallable(self, event_name)()
     61     except (CancelBatchException, CancelBackwardException, CancelEpochException, CancelFitException, CancelStepException, CancelTrainException, CancelValidException): raise
     62     except Exception as e: raise modify_exception(e, f'Exception occured in `{self.__class__.__name__}` when calling event `{event_name}`:\n\t{e.args[0]}', replace=True)

File /home/sp/torch/.venv/lib/python3.8/site-packages/fastai/learner.py:560, in Recorder.after_batch(self)
    558 if len(self.yb) == 0: return
    559 mets = self._train_mets if self.training else self._valid_mets
--> 560 for met in mets: met.accumulate(self.learn)
    561 if not self.training: return
    562 self.lrs.append(self.opt.hypers[-1]['lr'])

File /home/sp/torch/.venv/lib/python3.8/site-packages/fastai/learner.py:482, in AvgMetric.accumulate(self, learn)
    480 def accumulate(self, learn):
    481     bs = find_bs(learn.yb)
--> 482     self.total += learn.to_detach(self.func(learn.pred, *learn.yb))*bs
    483     self.count += bs

TypeError: Exception occured in `Recorder` when calling event `after_batch`:
	'str' object is not callable

Any suggestions on what I should do? My code is as follows:

from sklearn.datasets import load_iris
from fastai.tabular.all import *
import pandas as pd

iris = load_iris(as_frame=True)
columns = list(iris.data.columns)
df = pd.concat([iris.data, iris.target], axis=1)
dls = TabularDataLoaders.from_df(df, y_names="target", cont_names=columns, procs=[Categorify, FillMissing, Normalize])
learn = tabular_learner(dls, metrics="accuracy")
learn.fit_one_cycle(1)

You are passing a string to metrics whereas you want to pass the built-in fastai object accuracy like so:

Here’s an example notebook.

1 Like

Oh! That was a rather silly mistake on my part. Thanks!

1 Like