Tip: Use functools.partial to change metric keyword arguments

fbeta and other metrics have default keyword arguments and I was struggling to understand how to change their default arguments since a metric needs to be passed as a function to create_cnn().

For example:

bce_logits = F.binary_cross_entropy_with_logits
learn = create_cnn(data, tvm.resnet34, loss_func=bce_logits, metrics=[fbeta])

In my case I wanted to change fbeta’s default beta=2 to beta=1. I initially tried metrics=fbeta(beta=2) which obviously didn’t work because we need to pass a callable metrics function.

After a bit of searching I discovered python’s functools.partial method which allows you to pass values to a function and returns a callable function with your passed values! Super handy, it can be used like this:

from functools import partial
my_fbeta = partial(fbeta, beta=1)
learn = create_cnn(data, tvm.resnet34, loss_func=bce_logits, metrics=[my_fbeta])

Hopefully this helps others save some time.

3 Likes

We use it all the time in fastai :wink:
Note that you don’t need to import it separately, you get it with from fastai import *

1 Like

Nice! Thanks for the tip :slight_smile: