diff --git a/imblearn/metrics/_classification.py b/imblearn/metrics/_classification.py index c7ba87bf2..fa55fd69e 100644 --- a/imblearn/metrics/_classification.py +++ b/imblearn/metrics/_classification.py @@ -1131,7 +1131,8 @@ def macro_averaged_mean_absolute_error(y_true, y_pred, *, sample_weight=None): mae = [] for possible_class in labels: indices = np.flatnonzero(y_true == possible_class) - + if len(indices) == 0: + continue mae.append( mean_absolute_error( y_true[indices], @@ -1140,4 +1141,4 @@ def macro_averaged_mean_absolute_error(y_true, y_pred, *, sample_weight=None): ) ) - return np.sum(mae) / len(mae) + return np.mean(mae) if mae else 0.0 \ No newline at end of file diff --git a/imblearn/metrics/tests/test_classification.py b/imblearn/metrics/tests/test_classification.py index 422c27e57..36f23d65c 100644 --- a/imblearn/metrics/tests/test_classification.py +++ b/imblearn/metrics/tests/test_classification.py @@ -547,3 +547,11 @@ def test_macro_averaged_mean_absolute_error_sample_weight(): ) assert ma_mae_unit_weights == pytest.approx(ma_mae_no_weights) +def test_macro_averaged_mean_absolute_error_missing_class(): + # Regression test for issue #1094 + # Class 1 is missing in y_true, but exists in y_pred + y_true = [0, 0] + y_pred = [0, 1] + # Expected: (MAE for class 0 only) / 1 class = 0.5 + res = macro_averaged_mean_absolute_error(y_true, y_pred) + assert res == 0.5