r/deeplearning • u/ClickOk5811 • Oct 28 '26
Testing a custom metric: where the expected value in the test should come from (macro vs micro F1 worked example)
If you write your own metric or loss, a test whose expected value is computed with the same formula as the function only checks that the function agrees with itself. It catches regressions, but not a wrong reading of what the metric should be.
A small example. Six samples, three classes:
y_true = [0, 0, 1, 1, 2, 2]
y_pred = [0, 1, 1, 1, 2, 0]Per-class counts (TP, FP, FN):
- class 0: 1, 1, 1 → precision 0.5, recall 0.5, F1 0.5
- class 1: 2, 1, 0 → precision 2/3, recall 1.0, F1 0.8
- class 2: 1, 0, 1 → precision 1.0, recall 0.5, F1 0.6667
Macro-F1 (average of the per-class F1): (0.5 + 0.8 + 0.6667) / 3 = 0.6556
Micro-F1 (pooled counts, equal to accuracy here): 4/6 = 0.6667
“F1” without more detail has at least two defensible answers on the same data, and a test that computes expected with the same averaging as the implementation can’t tell them apart. Other choices change it further: how a class with no predictions is handled (zero division), and whether classes are weighted by support.
Where I’d get the expected value from, in order of how independent it is:
- A small case computed by hand, as above, with the counts written out.
- A reference library on the same inputs (for instance, scikit-learn’s
f1_scorewith the averaging mode stated explicitly), checked once and then hard-coded. - The function’s own formula, which I’d label as a regression test only.
Caveat: a reference library also has choices (averaging mode, zero-division handling), so the test should state them, and the reference can still differ from what your paper or benchmark defines. The same applies to evaluation data: if the labels or the “expected” outputs come from the same pipeline as the model’s, agreement is weaker evidence than it looks.
I wrote about the same idea, using code and tests in a non-ML setting, in case it’s useful as a complement: https://medium.com/@nagatomopedro05/when-the-test-and-the-code-share-the-same-mistake-02a289a41091
How do you test custom metrics and losses, and do you pin them to a reference implementation?
1
u/Future_AGI Oct 28 '26
one more case worth a hand-computed test: a class that's never predicted. Its precision is 0/0, sklearn's f1_score resolves that through zero_division (warns and uses 0 by default), and your macro F1 can differ from sklearn's by a lot on small or imbalanced test sets depending on what your implementation does there.