Fix ValueError in macro_averaged_mean_absolute_error for missing classes (#1094)#1168
Conversation
…ed_mean_absolute_error
|
Thanks for the fix — the diagnosis is right and the regression test is a good addition. I reviewed it next to the alternative PR #1172, which targets the same issue, and wanted to share a couple of observations. Approach. This PR keeps if len(indices) == 0:
continue
...
return np.mean(mae) if mae else 0.0That's functionally correct, but it handles the symptom rather than the cause: the loop still enumerates Two small things worth tidying if this is the one that lands:
Also worth adding a changelog entry under Either PR resolves the bug; my mild preference is the |
Problem
The function macro_averaged_mean_absolute_error currently crashes with a ValueError (Found array with 0 samples) when a label exists in the predictions (y_pred) or the global labels set, but is entirely absent from the ground truth (y_true). This happens because the function attempts to calculate mean_absolute_error on an empty slice of data.
Solution
This PR introduces a defensive check within the label iteration loop:
Skip Empty Classes: If a class has zero occurrences in y_true, the loop now continues to the next label instead of attempting a calculation on empty arrays.
Robust Return: Changed the final return to use np.mean(mae) with a fallback to 0.0. This prevents a potential ZeroDivisionError if all classes were somehow skipped.
Changes
Modified imblearn/metrics/_classification.py to add the if len(indices) == 0: continue safety guard.
Added a new regression test test_macro_averaged_mean_absolute_error_missing_class in imblearn/metrics/tests/test_classification.py to prevent future regressions.
Verification
Manual Test: Verified that the reproduction script provided in #1094 now returns 0.5 instead of crashing.
Automated Tests: Ran pytest imblearn/metrics/tests/test_classification.py and all 52 tests passed.
Fixes #1094