Fix ValueError in macro_averaged_mean_absolute_error for missing classes (#1094)#1168
Open
prodduturisindhurdy wants to merge 1 commit intoscikit-learn-contrib:masterfrom
Open
Conversation
…ed_mean_absolute_error
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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