Have you read https://docs.fast.ai/metrics.html#Creating-your-own-metric ? The metrics are calculated on each batch. Whenever there is a class in a batch with no images then you would divide by 0 and therefore get nan.
Precision is a little complicated because you shouldn’t simply take the average over the batches. Fortunately, we have Precision()
so don’t need to rewrite this.
Also worth reading is this great post on metrics.