From efb0e90208c145cd4780bcd2b329b2dfbd7f3106 Mon Sep 17 00:00:00 2001 From: AryanRG Date: Mon, 19 Oct 2026 18:39:33 +0530 Subject: [PATCH 01/14] Use full training labels for holdout classification scoring --- flaml/automl/ml.py | 9 ++- flaml/automl/state.py | 1 + test/automl/test_holdout_labels.py | 106 +++++++++++++++++++++++++++++ 3 files changed, 115 insertions(+), 1 deletion(-) create mode 100644 test/automl/test_holdout_labels.py diff --git a/flaml/automl/ml.py b/flaml/automl/ml.py index a21e35b7e3..3e8ca06b0d 100644 --- a/flaml/automl/ml.py +++ b/flaml/automl/ml.py @@ -12,6 +12,7 @@ from flaml.automl.model import BaseEstimator, TransformersEstimator from flaml.automl.spark import ERROR as SPARK_ERROR from flaml.automl.spark import DataFrame, Series, psDataFrame, psSeries +from flaml.automl.spark.utils import len_labels from flaml.automl.task.task import Task from flaml.automl.time_series import TimeSeriesDataset @@ -350,6 +351,7 @@ def compute_estimator( log_training_metric: Optional[bool] = False, fit_kwargs: Optional[dict] = None, free_mem_ratio=0, + y_train_all=None, ): if fit_kwargs is None: fit_kwargs = {} @@ -376,6 +378,11 @@ def compute_estimator( fit_kwargs["y_val"] = y_val if "holdout" == eval_method: + labels = fit_kwargs.get("label_list") # pass the label list on to compute the evaluation metric + if labels is None and y_train is not None and task.is_classification() and not task.is_token_classification(): + # Match evaluate_model_CV: a trial's sample can omit a class, so use + # the full training targets when choosing labels for its metric. + _, labels = len_labels(y_train if y_train_all is None else y_train_all, return_labels=True) val_loss, metric_for_logging, train_time, pred_time = get_val_loss( config_dic, estimator, @@ -387,7 +394,7 @@ def compute_estimator( groups_val, eval_metric, task, - labels=fit_kwargs.get("label_list"), # pass the label list on to compute the evaluation metric + labels=labels, budget=budget, log_training_metric=log_training_metric, fit_kwargs=fit_kwargs, diff --git a/flaml/automl/state.py b/flaml/automl/state.py index e5469e1ebe..31b6ae4bcf 100644 --- a/flaml/automl/state.py +++ b/flaml/automl/state.py @@ -323,6 +323,7 @@ def _compute_with_config_base( state.log_training_metric, this_estimator_kwargs, state.free_mem_ratio, + y_train_all=state.y_train_all, ) if state.retrain_final and not state.model_history: trained_estimator.cleanup() diff --git a/test/automl/test_holdout_labels.py b/test/automl/test_holdout_labels.py new file mode 100644 index 0000000000..0062da4f18 --- /dev/null +++ b/test/automl/test_holdout_labels.py @@ -0,0 +1,106 @@ +import numpy as np +import pytest +from sklearn.metrics import f1_score, log_loss + +from flaml import AutoML + +SETTINGS = { + "task": "classification", + "estimator_list": ["lrl1"], + "max_iter": 3, + "n_jobs": 1, + "verbose": 0, + "retrain_full": False, +} + + +def _three_class_data(n=240, seed=0): + rng = np.random.RandomState(seed) + y = np.arange(n) % 3 + X = rng.randn(n, 4) + X[:, 0] += 2 * y + return X, y + + +def test_log_loss_with_validation_set_missing_a_class(): + X, y = _three_class_data() + X_train, y_train = X[:180], y[:180] + keep = y[180:] != 2 + X_val, y_val = X[180:][keep], y[180:][keep] + + automl = AutoML() + automl.fit(X_train, y_train, X_val=X_val, y_val=y_val, metric="log_loss", **SETTINGS) + + assert automl.best_estimator == "lrl1" + expected = log_loss(y_val, automl.predict_proba(X_val), labels=automl.classes_) + assert automl.best_loss == pytest.approx(expected) + + +def test_time_split_with_class_absent_from_latest_rows(): + X, y = _three_class_data(n=300) + y[-60:] = np.where(y[-60:] == 2, 0, y[-60:]) + + automl = AutoML() + automl.fit(X, y, eval_method="holdout", split_type="time", split_ratio=0.2, **SETTINGS) + + assert automl.best_estimator == "lrl1" + assert np.isfinite(automl.best_loss) + + +@pytest.mark.parametrize("eval_method", ["holdout", "cv"]) +def test_custom_metric_receives_training_labels(eval_method): + X, y = _three_class_data() + received = [] + + def custom_metric(X_val, y_val, estimator, labels, *args, **kwargs): + received.append(labels) + return 0.5, {} + + automl = AutoML() + automl.fit(X, y, metric=custom_metric, eval_method=eval_method, n_splits=3, **SETTINGS) + + assert received + assert all(np.array_equal(labels, [0, 1, 2]) for labels in received) + + +def test_sampled_holdout_uses_full_training_labels(): + rng = np.random.RandomState(1) + y = rng.choice([0, 1], size=3000) + y[rng.choice(len(y), 40, replace=False)] = 2 + X = rng.randn(len(y), 4) + X[:, 0] += 2 * y + y_val = np.arange(300) % 3 + X_val = rng.randn(len(y_val), 4) + X_val[:, 0] += 2 * y_val + sampled_classes = [] + + def macro_f1(X_val, y_val, estimator, labels, *args, **kwargs): + sampled_classes.append(estimator.classes_) + assert np.array_equal(labels, [0, 1, 2]) + predictions = estimator.predict(X_val) + score = f1_score(y_val, predictions, labels=labels, average="macro") + expected = f1_score(y_val, predictions, labels=[0, 1, 2], average="macro") + assert score == pytest.approx(expected) + return 1 - score, {} + + automl = AutoML() + automl.fit( + X, + y, + X_val=X_val, + y_val=y_val, + task="classification", + metric=macro_f1, + estimator_list=["lgbm"], + max_iter=6, + min_sample_size=50, + sample=True, + starting_points={}, + auto_augment=False, + n_jobs=1, + verbose=0, + retrain_full=False, + ) + + assert any(len(classes) == 2 for classes in sampled_classes) + assert np.isfinite(automl.best_loss) From dd0c080b4f40600441ec26f6ccc042f279cfc9d0 Mon Sep 17 00:00:00 2001 From: AryanRG Date: Mon, 19 Oct 2026 20:42:48 +0530 Subject: [PATCH 02/14] Align sampled scoring probabilities and cache training labels --- flaml/automl/automl.py | 12 +++ flaml/automl/ml.py | 32 +++++- flaml/automl/state.py | 1 + test/automl/test_holdout_labels.py | 158 +++++++++++++++++++++++++++++ 4 files changed, 202 insertions(+), 1 deletion(-) diff --git a/flaml/automl/automl.py b/flaml/automl/automl.py index 1daccaebe1..1cdc9943cd 100644 --- a/flaml/automl/automl.py +++ b/flaml/automl/automl.py @@ -26,6 +26,7 @@ train_estimator, ) from flaml.automl.spark import DataFrame, Series, psDataFrame, psSeries +from flaml.automl.spark.utils import len_labels from flaml.automl.state import AutoMLState, SearchState from flaml.automl.task.factory import task_factory @@ -1844,6 +1845,8 @@ def metric_constraints(self) -> list: return self._metric_constraints def _prepare_data(self, eval_method, split_ratio, n_splits): + # Reset on every fit, including when the same AutoML changes tasks. + self._state.holdout_labels = None self._state.task.prepare_data( self._state, self._X_train_all, @@ -1857,6 +1860,15 @@ def _prepare_data(self, eval_method, split_ratio, n_splits): self._sample_weight_full, self._allow_label_overlap, ) + if ( + eval_method == "holdout" + and self._state.task.is_classification() + and not self._state.task.is_token_classification() + and self._state.y_train_all is not None + ): + _, labels = len_labels(self._state.y_train_all, return_labels=True) + # Do not retain a live pandas-on-Spark object in serialized state. + self._state.holdout_labels = labels.to_numpy() if isinstance(labels, psSeries) else labels self.data_size_full = self._state.data_size_full def fit( diff --git a/flaml/automl/ml.py b/flaml/automl/ml.py index 3e8ca06b0d..da95aebb69 100644 --- a/flaml/automl/ml.py +++ b/flaml/automl/ml.py @@ -13,6 +13,7 @@ from flaml.automl.spark import ERROR as SPARK_ERROR from flaml.automl.spark import DataFrame, Series, psDataFrame, psSeries from flaml.automl.spark.utils import len_labels +from flaml.automl.task.factory import task_factory from flaml.automl.task.task import Task from flaml.automl.time_series import TimeSeriesDataset @@ -352,7 +353,10 @@ def compute_estimator( fit_kwargs: Optional[dict] = None, free_mem_ratio=0, y_train_all=None, + training_labels=None, ): + if isinstance(task, str): + task = task_factory(task, X_train, y_train) if fit_kwargs is None: fit_kwargs = {} @@ -382,7 +386,9 @@ def compute_estimator( if labels is None and y_train is not None and task.is_classification() and not task.is_token_classification(): # Match evaluate_model_CV: a trial's sample can omit a class, so use # the full training targets when choosing labels for its metric. - _, labels = len_labels(y_train if y_train_all is None else y_train_all, return_labels=True) + labels = training_labels + if labels is None: + _, labels = len_labels(y_train if y_train_all is None else y_train_all, return_labels=True) val_loss, metric_for_logging, train_time, pred_time = get_val_loss( config_dic, estimator, @@ -587,6 +593,26 @@ def default_cv_score_agg_func(val_loss_folds, log_metrics_folds): return metric_to_minimize, metrics_to_log +def _align_log_loss_probabilities(predictions, estimator, labels): + """Match sampled classifiers' probability columns to log_loss's label order.""" + if labels is None or isinstance(predictions, (psDataFrame, psSeries)): + return predictions + classes = getattr(estimator, "classes_", None) + probabilities = np.asarray(predictions) + if classes is None or probabilities.ndim != 2 or probabilities.shape[1] != len(classes): + return predictions + # sklearn's log_loss sorts labels, even when an explicit override is unsorted. + labels = np.unique(labels) + if np.array_equal(classes, labels): + return predictions + positions = {label: index for index, label in enumerate(labels)} + if any(label not in positions for label in classes): + return predictions + aligned = np.zeros((len(probabilities), len(labels)), dtype=probabilities.dtype) + aligned[:, [positions[label] for label in classes]] = probabilities + return aligned + + def _eval_estimator( config, estimator, @@ -605,6 +631,8 @@ def _eval_estimator( if isinstance(eval_metric, str): pred_start = time.time() val_pred_y = get_y_pred(estimator, X_val, eval_metric, task) + if eval_metric == "log_loss": + val_pred_y = _align_log_loss_probabilities(val_pred_y, estimator, labels) # TODO: why are integer labels being cast to str in the first place? @@ -644,6 +672,8 @@ def _eval_estimator( # aligned and avoid empty prediction inputs. X_train_for_metric = X_val.X_train if isinstance(X_val, TimeSeriesDataset) else X_train train_pred_y = get_y_pred(estimator, X_train_for_metric, eval_metric, task) + if eval_metric == "log_loss": + train_pred_y = _align_log_loss_probabilities(train_pred_y, estimator, labels) metric_for_logging["train_loss"] = metric_loss_score( eval_metric, train_pred_y, diff --git a/flaml/automl/state.py b/flaml/automl/state.py index 31b6ae4bcf..9c35a359f9 100644 --- a/flaml/automl/state.py +++ b/flaml/automl/state.py @@ -324,6 +324,7 @@ def _compute_with_config_base( this_estimator_kwargs, state.free_mem_ratio, y_train_all=state.y_train_all, + training_labels=getattr(state, "holdout_labels", None), ) if state.retrain_final and not state.model_history: trained_estimator.cleanup() diff --git a/test/automl/test_holdout_labels.py b/test/automl/test_holdout_labels.py index 0062da4f18..b99a466dd1 100644 --- a/test/automl/test_holdout_labels.py +++ b/test/automl/test_holdout_labels.py @@ -1,8 +1,12 @@ +from types import SimpleNamespace + import numpy as np import pytest from sklearn.metrics import f1_score, log_loss from flaml import AutoML +from flaml.automl import ml +from flaml.automl.model import LRL1Classifier SETTINGS = { "task": "classification", @@ -104,3 +108,157 @@ def macro_f1(X_val, y_val, estimator, labels, *args, **kwargs): assert any(len(classes) == 2 for classes in sampled_classes) assert np.isfinite(automl.best_loss) + + +@pytest.mark.parametrize("validation_has_rare_class", [False, True]) +def test_sampled_log_loss_with_training_metric(monkeypatch, validation_has_rare_class): + rng = np.random.RandomState(1) + y = rng.choice([0, 1], size=3000) + y[rng.choice(len(y), 40, replace=False)] = 2 + X = rng.randn(len(y), 4) + X[:, 0] += 2 * y + y_val = np.arange(300) % (3 if validation_has_rare_class else 2) + X_val = rng.randn(len(y_val), 4) + X_val[:, 0] += 2 * y_val + sampled_classes = [] + original = ml._eval_estimator + + def recording(config, estimator, X_train, y_train, X_val, y_val, *args, **kwargs): + result = original(config, estimator, X_train, y_train, X_val, y_val, *args, **kwargs) + sampled_classes.append(estimator.classes_) + for features, target, actual in ( + (X_val, y_val, result[0]), + (X_train, y_train, result[1]["train_loss"]), + ): + probabilities = np.zeros((len(target), 3)) + probabilities[:, estimator.classes_.astype(int)] = estimator.predict_proba(features) + assert actual == pytest.approx(log_loss(target, probabilities, labels=[0, 1, 2])) + assert np.isfinite(actual) + return result + + monkeypatch.setattr(ml, "_eval_estimator", recording) + automl = AutoML() + automl.fit( + X, + y, + X_val=X_val, + y_val=y_val, + task="classification", + metric="log_loss", + log_training_metric=True, + estimator_list=["lgbm"], + max_iter=6, + min_sample_size=50, + sample=True, + starting_points={}, + auto_augment=False, + n_jobs=1, + verbose=0, + retrain_full=False, + ) + assert any(len(classes) == 2 for classes in sampled_classes) + assert np.isfinite(automl.best_loss) + + +def test_compute_estimator_accepts_string_task(): + X, y = _three_class_data() + result = ml.compute_estimator( + X[:180], + y[:180], + X[180:], + y[180:], + None, + None, + None, + None, + {"C": 1.0}, + "classification", + "lrl1", + "holdout", + "accuracy", + estimator_class=LRL1Classifier, + ) + assert np.isfinite(result[1]) + + +@pytest.mark.parametrize( + "classes, labels, expected", + [ + ([2, 0], [0, 1, 2], [[0.8, 0.0, 0.2]]), + (["z", "a"], ["z", "a", "m"], [[0.8, 0.0, 0.2]]), + ([0, 1], [1, 0], [[0.2, 0.8]]), + ], +) +def test_log_loss_probability_column_alignment(classes, labels, expected): + probabilities = np.array([[0.2, 0.8]]) + estimator = SimpleNamespace(classes_=np.array(classes)) + actual = ml._align_log_loss_probabilities(probabilities, estimator, labels) + np.testing.assert_allclose(actual, expected) + + +def test_explicit_label_list_overrides_cached_labels(): + X, y = _three_class_data() + received = [] + + class Estimator: + def __init__(self, **kwargs): + pass + + def fit(self, *args, **kwargs): + pass + + def custom_metric(X_val, y_val, estimator, labels, *args, **kwargs): + received.append(labels) + return 0.5, {} + + override = ["explicit", "labels"] + ml.compute_estimator( + X[:180], + y[:180], + X[180:], + y[180:], + None, + None, + None, + None, + {}, + "classification", + "custom", + "holdout", + custom_metric, + estimator_class=Estimator, + fit_kwargs={"label_list": override}, + training_labels=np.array([0, 1, 2]), + ) + assert received == [override] + + +def test_holdout_labels_cached_and_refreshed_per_fit(monkeypatch): + X, y = _three_class_data() + calls = [] + original = ml.len_labels + + def counting(values, *args, **kwargs): + calls.append(len(values)) + return original(values, *args, **kwargs) + + monkeypatch.setattr(ml, "len_labels", counting) + automl = AutoML() + for current_y in (y, y % 2): + seen = [] + + def custom_metric(X_val, y_val, estimator, labels, *args, **kwargs): + seen.append(labels) + return 0.5, {} + + automl.fit( + X[:180], + current_y[:180], + X_val=X[180:], + y_val=current_y[180:], + metric=custom_metric, + **SETTINGS, + ) + assert seen + assert all(np.array_equal(labels, np.unique(current_y)) for labels in seen) + assert calls == [] From 93b8931ae2682918cb68c9e74076540fa4b713e0 Mon Sep 17 00:00:00 2001 From: AryanRG Date: Tue, 20 Oct 2026 02:53:09 +0530 Subject: [PATCH 03/14] Preserve custom metric label inference and isolate callback labels --- flaml/automl/ml.py | 11 ++++- test/automl/test_holdout_labels.py | 68 ++++++++++++++++++++++++++++-- 2 files changed, 73 insertions(+), 6 deletions(-) diff --git a/flaml/automl/ml.py b/flaml/automl/ml.py index da95aebb69..c75b3b5e1d 100644 --- a/flaml/automl/ml.py +++ b/flaml/automl/ml.py @@ -4,6 +4,7 @@ # * project root for license information. import logging import time +from copy import copy from typing import Callable, Optional, Tuple, TypeVar, Union import numpy as np @@ -383,7 +384,13 @@ def compute_estimator( if "holdout" == eval_method: labels = fit_kwargs.get("label_list") # pass the label list on to compute the evaluation metric - if labels is None and y_train is not None and task.is_classification() and not task.is_token_classification(): + if ( + labels is None + and isinstance(eval_metric, str) + and y_train is not None + and task.is_classification() + and not task.is_token_classification() + ): # Match evaluate_model_CV: a trial's sample can omit a class, so use # the full training targets when choosing labels for its metric. labels = training_labels @@ -687,7 +694,7 @@ def _eval_estimator( X_val, y_val, estimator, - labels, + copy(labels), X_train, y_train, weight_val, diff --git a/test/automl/test_holdout_labels.py b/test/automl/test_holdout_labels.py index b99a466dd1..9a6fee3a0d 100644 --- a/test/automl/test_holdout_labels.py +++ b/test/automl/test_holdout_labels.py @@ -64,10 +64,13 @@ def custom_metric(X_val, y_val, estimator, labels, *args, **kwargs): automl.fit(X, y, metric=custom_metric, eval_method=eval_method, n_splits=3, **SETTINGS) assert received - assert all(np.array_equal(labels, [0, 1, 2]) for labels in received) + if eval_method == "holdout": + assert all(labels is None for labels in received) + else: + assert all(np.array_equal(labels, [0, 1, 2]) for labels in received) -def test_sampled_holdout_uses_full_training_labels(): +def test_sampled_holdout_custom_metric_keeps_label_inference(): rng = np.random.RandomState(1) y = rng.choice([0, 1], size=3000) y[rng.choice(len(y), 40, replace=False)] = 2 @@ -80,7 +83,7 @@ def test_sampled_holdout_uses_full_training_labels(): def macro_f1(X_val, y_val, estimator, labels, *args, **kwargs): sampled_classes.append(estimator.classes_) - assert np.array_equal(labels, [0, 1, 2]) + assert labels is None predictions = estimator.predict(X_val) score = f1_score(y_val, predictions, labels=labels, average="macro") expected = f1_score(y_val, predictions, labels=[0, 1, 2], average="macro") @@ -110,6 +113,62 @@ def macro_f1(X_val, y_val, estimator, labels, *args, **kwargs): assert np.isfinite(automl.best_loss) +def test_documented_callable_log_loss_with_sampled_estimator(): + rng = np.random.RandomState(1) + y = rng.choice([0, 1], size=3000) + y[rng.choice(len(y), 40, replace=False)] = 2 + X = rng.randn(len(y), 4) + X[:, 0] += 2 * y + y_val = np.arange(300) % 2 + X_val = rng.randn(len(y_val), 4) + X_val[:, 0] += 2 * y_val + sampled_classes = [] + + def custom_metric(X_val, y_val, estimator, labels, X_train, y_train, weight_val, weight_train, *args): + sampled_classes.append(estimator.classes_.copy()) + val_loss = log_loss(y_val, estimator.predict_proba(X_val), labels=labels, sample_weight=weight_val) + train_loss = log_loss(y_train, estimator.predict_proba(X_train), labels=labels, sample_weight=weight_train) + return 1.5 * val_loss - 0.5 * train_loss, {"val_loss": val_loss, "train_loss": train_loss} + + automl = AutoML() + automl.fit( + X, + y, + X_val=X_val, + y_val=y_val, + task="classification", + metric=custom_metric, + estimator_list=["lgbm"], + max_iter=2, + seed=1, + min_sample_size=50, + sample=True, + starting_points={}, + auto_augment=False, + n_jobs=1, + verbose=0, + retrain_full=False, + ) + assert any(len(classes) == 2 for classes in sampled_classes) + assert np.isfinite(automl.best_loss) + + +def test_custom_metric_cannot_mutate_shared_labels(): + X, y = _three_class_data() + labels = np.array([0, 1, 2]) + received = [] + + def mutating_metric(X_val, y_val, estimator, callback_labels, *args): + received.append(callback_labels.copy()) + callback_labels[0] = 99 + return 0.5, {} + + for _ in range(2): + ml._eval_estimator({}, object(), X, y, X, y, None, None, mutating_metric, "classification", labels) + assert all(np.array_equal(value, [0, 1, 2]) for value in received) + np.testing.assert_array_equal(labels, [0, 1, 2]) + + @pytest.mark.parametrize("validation_has_rare_class", [False, True]) def test_sampled_log_loss_with_training_metric(monkeypatch, validation_has_rare_class): rng = np.random.RandomState(1) @@ -260,5 +319,6 @@ def custom_metric(X_val, y_val, estimator, labels, *args, **kwargs): **SETTINGS, ) assert seen - assert all(np.array_equal(labels, np.unique(current_y)) for labels in seen) + assert all(labels is None for labels in seen) + np.testing.assert_array_equal(automl._state.holdout_labels, np.unique(current_y)) assert calls == [] From e3046451d9201ac966a8708631e1a3df2b74b4f5 Mon Sep 17 00:00:00 2001 From: AryanRG Date: Tue, 20 Oct 2026 10:36:25 +0530 Subject: [PATCH 04/14] Handle single-class boosted samples in multiclass log loss --- flaml/automl/ml.py | 19 ++++- test/automl/test_holdout_labels.py | 109 ++++++++++++++++++++++++++++- 2 files changed, 125 insertions(+), 3 deletions(-) diff --git a/flaml/automl/ml.py b/flaml/automl/ml.py index c75b3b5e1d..353be8ad5a 100644 --- a/flaml/automl/ml.py +++ b/flaml/automl/ml.py @@ -8,9 +8,10 @@ from typing import Callable, Optional, Tuple, TypeVar, Union import numpy as np +from xgboost import XGBClassifier from flaml.automl.data import group_counts -from flaml.automl.model import BaseEstimator, TransformersEstimator +from flaml.automl.model import BaseEstimator, LGBMClassifier, TransformersEstimator from flaml.automl.spark import ERROR as SPARK_ERROR from flaml.automl.spark import DataFrame, Series, psDataFrame, psSeries from flaml.automl.spark.utils import len_labels @@ -606,7 +607,21 @@ def _align_log_loss_probabilities(predictions, estimator, labels): return predictions classes = getattr(estimator, "classes_", None) probabilities = np.asarray(predictions) - if classes is None or probabilities.ndim != 2 or probabilities.shape[1] != len(classes): + if classes is None or probabilities.ndim != 2: + return predictions + # For multiclass scoring, these binary APIs can emit an implicit second class. + # Normalize over the sole observed class; binary scoring keeps both columns. + if ( + len(classes) == 1 + and probabilities.shape[1] == 2 + and len(np.unique(labels)) > 2 + and ( + isinstance(getattr(estimator, "model", estimator), XGBClassifier) + or (LGBMClassifier is not None and isinstance(getattr(estimator, "model", estimator), LGBMClassifier)) + ) + ): + probabilities = np.ones_like(probabilities[:, :1]) + if probabilities.shape[1] != len(classes): return predictions # sklearn's log_loss sorts labels, even when an explicit override is unsorted. labels = np.unique(labels) diff --git a/test/automl/test_holdout_labels.py b/test/automl/test_holdout_labels.py index 9a6fee3a0d..881dccfd51 100644 --- a/test/automl/test_holdout_labels.py +++ b/test/automl/test_holdout_labels.py @@ -3,10 +3,11 @@ import numpy as np import pytest from sklearn.metrics import f1_score, log_loss +from xgboost import XGBClassifier from flaml import AutoML from flaml.automl import ml -from flaml.automl.model import LRL1Classifier +from flaml.automl.model import LGBMEstimator, LRL1Classifier SETTINGS = { "task": "classification", @@ -240,6 +241,112 @@ def test_compute_estimator_accepts_string_task(): assert np.isfinite(result[1]) +@pytest.mark.parametrize("learner", ["lgbm", "xgboost", "xgb_limitdepth"]) +@pytest.mark.parametrize("log_training_metric", [False, True]) +@pytest.mark.parametrize("num_classes", [2, 3]) +def test_single_class_boosted_sample_has_finite_log_loss(monkeypatch, log_training_metric, learner, num_classes): + rng = np.random.RandomState(81) + y = np.zeros(3000, dtype=int) + y[1500], y[2500] = 1, num_classes - 1 + X = rng.randn(len(y), 4) + y_val = (np.arange(300) % 5 == 0).astype(int) if num_classes == 2 else np.arange(300) % 2 + X_val = rng.randn(len(y_val), 4) + sampled_classes = [] + original = ml._eval_estimator + + def recording(config, estimator, X_train, y_train, X_val, y_val, *args, **kwargs): + result = original(config, estimator, X_train, y_train, X_val, y_val, *args, **kwargs) + sampled_classes.append(estimator.classes_.copy()) + cases = [(X_val, y_val, result[0])] + if log_training_metric: + cases.append((X_train, y_train, result[1]["train_loss"])) + for features, target, actual in cases: + raw = estimator.predict_proba(features) + assert raw.shape == (len(target), 2) + if num_classes == 2: + expected = raw + else: + expected = np.zeros((len(target), num_classes), dtype=raw.dtype) + expected[:, 0] = 1.0 + assert np.isfinite(actual) + assert actual == pytest.approx(log_loss(target, expected, labels=np.arange(num_classes))) + return result + + monkeypatch.setattr(ml, "_eval_estimator", recording) + automl = AutoML() + automl.fit( + X, + y, + X_val=X_val, + y_val=y_val, + task="classification", + metric="log_loss", + log_training_metric=log_training_metric, + estimator_list=[learner], + max_iter=2, + seed=1, + min_sample_size=50, + sample=True, + starting_points={}, + auto_augment=False, + n_jobs=1, + verbose=0, + retrain_full=False, + ) + assert len(sampled_classes) == 2 + assert all(np.array_equal(classes, [0]) for classes in sampled_classes) + assert np.isfinite(automl.best_loss) + assert automl.model is not None + + +@pytest.mark.parametrize( + "sole_class, labels", + [(0, [0, 1, 2]), (1, [2, 1, 0]), (7, [1, 7, 3]), ("b", ["c", "b", "a"])], +) +@pytest.mark.parametrize("wrapped", [False, True]) +def test_single_class_lightgbm_probability_alignment(sole_class, labels, wrapped): + X = np.random.RandomState(81).randn(20, 4) + estimator = LGBMEstimator(task="classification", n_estimators=2, n_jobs=1, verbosity=-1) + estimator.fit(X, np.full(len(X), sole_class)) + raw = estimator.predict_proba(X) + assert raw.shape == (len(X), 2) + np.testing.assert_array_equal(estimator.classes_, [sole_class]) + before = raw.copy() + actual = ml._align_log_loss_probabilities(raw, estimator if wrapped else estimator.model, labels) + expected = np.zeros((len(X), len(labels))) + expected[:, list(np.unique(labels)).index(sole_class)] = 1.0 + np.testing.assert_allclose(actual, expected) + np.testing.assert_array_equal(raw, before) + + +@pytest.mark.parametrize("wrapped", [False, True]) +def test_single_class_xgboost_probability_alignment(wrapped): + X = np.random.RandomState(81).randn(20, 4) + estimator = XGBClassifier(n_estimators=2, n_jobs=1) + estimator.fit(X, np.zeros(len(X), dtype=int)) + raw = estimator.predict_proba(X) + assert raw.shape == (len(X), 2) + before = raw.copy() + classifier = SimpleNamespace(model=estimator, classes_=estimator.classes_) if wrapped else estimator + actual = ml._align_log_loss_probabilities(raw, classifier, [2, 0, 1]) + np.testing.assert_array_equal(actual, np.tile([1.0, 0.0, 0.0], (len(X), 1))) + np.testing.assert_array_equal(actual.sum(axis=1), np.ones(len(X))) + np.testing.assert_array_equal(raw, before) + + +def test_unknown_single_class_estimator_keeps_unexpected_probability_width(): + raw = np.array([[0.2, 0.8]]) + estimator = SimpleNamespace(classes_=np.array([0])) + assert ml._align_log_loss_probabilities(raw, estimator, [0, 1, 2]) is raw + + +def test_probability_width_guard_without_lightgbm(monkeypatch): + monkeypatch.setattr(ml, "LGBMClassifier", None, raising=False) + raw = np.array([[0.2, 0.8]]) + estimator = SimpleNamespace(classes_=np.array([0])) + assert ml._align_log_loss_probabilities(raw, estimator, [0, 1, 2]) is raw + + @pytest.mark.parametrize( "classes, labels, expected", [ From 5b3678ea1e618b20376853e3436c44f94fa29c96 Mon Sep 17 00:00:00 2001 From: AryanRG Date: Mon, 26 Oct 2026 19:04:33 +0530 Subject: [PATCH 05/14] Align public probabilities with the full class set --- flaml/automl/automl.py | 10 +++ test/automl/test_holdout_labels.py | 131 ++++++++++++++++++++++++++++- 2 files changed, 138 insertions(+), 3 deletions(-) diff --git a/flaml/automl/automl.py b/flaml/automl/automl.py index 1cdc9943cd..5fabcc322e 100644 --- a/flaml/automl/automl.py +++ b/flaml/automl/automl.py @@ -20,6 +20,7 @@ from flaml import tune from flaml.automl.logger import logger, logger_formatter from flaml.automl.ml import ( + _align_log_loss_probabilities, huggingface_metric_to_mode, sklearn_metric_name_set, spark_metric_name_dict, @@ -912,6 +913,15 @@ def predict_proba(self, X, **pred_kwargs): return None X = self._state.task.preprocess(X, self._transformer) proba = self._trained_estimator.predict_proba(X, **pred_kwargs) + if ( + self._state.task.name in ("classification", "binary", "multiclass") + and self._label_transformer + and not any(pred_kwargs.get(option) for option in ("raw_score", "pred_leaf", "pred_contrib")) + ): + # The estimator uses encoded labels; public columns follow classes_. + # Raw scores, leaf indices and feature contributions are not probabilities. + labels = np.arange(len(self._label_transformer.classes_)) + proba = _align_log_loss_probabilities(proba, estimator, labels) return proba def preprocess( diff --git a/test/automl/test_holdout_labels.py b/test/automl/test_holdout_labels.py index 881dccfd51..97180b8a66 100644 --- a/test/automl/test_holdout_labels.py +++ b/test/automl/test_holdout_labels.py @@ -52,6 +52,27 @@ def test_time_split_with_class_absent_from_latest_rows(): assert np.isfinite(automl.best_loss) +@pytest.mark.parametrize("skip_transform", [False, True]) +@pytest.mark.parametrize("retrain_full", [False, True]) +def test_public_probabilities_with_complete_class_set(skip_transform, retrain_full): + X, y = _three_class_data() + automl = AutoML() + automl.fit( + X[:180], + y[:180], + X_val=X[180:], + y_val=y[180:], + metric="log_loss", + sample=False, + skip_transform=skip_transform, + **{**SETTINGS, "retrain_full": retrain_full}, + ) + + raw = automl.model.predict_proba(automl.preprocess(X[180:])) + np.testing.assert_array_equal(automl.predict_proba(X[180:]), raw) + np.testing.assert_array_equal(automl.classes_, [0, 1, 2]) + + @pytest.mark.parametrize("eval_method", ["holdout", "cv"]) def test_custom_metric_receives_training_labels(eval_method): X, y = _three_class_data() @@ -244,13 +265,17 @@ def test_compute_estimator_accepts_string_task(): @pytest.mark.parametrize("learner", ["lgbm", "xgboost", "xgb_limitdepth"]) @pytest.mark.parametrize("log_training_metric", [False, True]) @pytest.mark.parametrize("num_classes", [2, 3]) -def test_single_class_boosted_sample_has_finite_log_loss(monkeypatch, log_training_metric, learner, num_classes): +@pytest.mark.parametrize("string_labels", [False, True]) +def test_single_class_boosted_sample_has_finite_log_loss( + monkeypatch, log_training_metric, learner, num_classes, string_labels +): rng = np.random.RandomState(81) y = np.zeros(3000, dtype=int) y[1500], y[2500] = 1, num_classes - 1 X = rng.randn(len(y), 4) y_val = (np.arange(300) % 5 == 0).astype(int) if num_classes == 2 else np.arange(300) % 2 X_val = rng.randn(len(y_val), 4) + labels = np.array(["a", "b", "c"][:num_classes]) if string_labels else 10 * (np.arange(num_classes) + 1) sampled_classes = [] original = ml._eval_estimator @@ -276,9 +301,9 @@ def recording(config, estimator, X_train, y_train, X_val, y_val, *args, **kwargs automl = AutoML() automl.fit( X, - y, + labels[y], X_val=X_val, - y_val=y_val, + y_val=labels[y_val], task="classification", metric="log_loss", log_training_metric=log_training_metric, @@ -297,6 +322,106 @@ def recording(config, estimator, X_train, y_train, X_val, y_val, *args, **kwargs assert all(np.array_equal(classes, [0]) for classes in sampled_classes) assert np.isfinite(automl.best_loss) assert automl.model is not None + raw = automl.model.predict_proba(automl.preprocess(X_val)) + probabilities = automl.predict_proba(X_val) + assert probabilities.shape == (len(y_val), num_classes) + np.testing.assert_array_equal(automl.classes_, labels) + np.testing.assert_allclose(probabilities.sum(axis=1), 1) + if num_classes == 2: + np.testing.assert_array_equal(probabilities, raw) + else: + np.testing.assert_array_equal(probabilities[:, 0], 1) + np.testing.assert_array_equal(probabilities[:, 1:], 0) + assert log_loss(labels[y_val], probabilities, labels=automl.classes_) == pytest.approx(automl.best_loss) + np.testing.assert_array_equal(automl.model.predict_proba(automl.preprocess(X_val)), raw) + + +@pytest.mark.parametrize("output", ["raw_score", "pred_leaf", "pred_contrib", None]) +def test_sampled_lightgbm_prediction_options(output): + rng = np.random.RandomState(81) + y = np.zeros(3000, dtype=int) + y[1500], y[2500] = 1, 2 + # One feature makes contribution scores have the same width as binary probabilities. + X = rng.randn(len(y), 1) + X_val = rng.randn(300, 1) + automl = AutoML() + automl.fit( + X, + y, + X_val=X_val, + y_val=np.arange(len(X_val)) % 2, + task="classification", + metric="log_loss", + estimator_list=["lgbm"], + max_iter=2, + seed=1, + min_sample_size=50, + sample=True, + starting_points={}, + auto_augment=False, + n_jobs=1, + verbose=0, + retrain_full=False, + ) + np.testing.assert_array_equal(automl.model.classes_, [0]) + kwargs = {"num_iteration": 2} + if output is not None: + kwargs[output] = True + raw = automl.model.predict_proba(automl.preprocess(X_val), **kwargs) + actual = automl.predict_proba(X_val, **kwargs) + if output is None: + assert actual.shape == (len(X_val), len(automl.classes_)) + np.testing.assert_array_equal(actual[:, 0], 1) + np.testing.assert_array_equal(actual[:, 1:], 0) + else: + np.testing.assert_array_equal(actual, raw) + + +@pytest.mark.parametrize("missing_class", [0, 1, 2]) +@pytest.mark.parametrize("learner", ["lgbm", "rf"]) +def test_public_probabilities_from_sampled_classifier(missing_class, learner): + rng = np.random.RandomState(1) + present_classes = np.delete(np.arange(3), missing_class) + y = rng.choice(present_classes, size=3000) + y[rng.choice(len(y), 40, replace=False)] = missing_class + X = rng.randn(len(y), 4) + X[:, 0] += 2 * y + y_val = np.arange(300) % 3 + X_val = rng.randn(len(y_val), 4) + X_val[:, 0] += 2 * y_val + labels = np.array(["alpha", "beta", "gamma"]) + + automl = AutoML() + automl.fit( + X, + labels[y], + X_val=X_val, + y_val=labels[y_val], + task="classification", + metric="log_loss", + estimator_list=[learner], + max_iter=2, + seed=1, + min_sample_size=50, + sample=True, + starting_points={}, + auto_augment=False, + n_jobs=1, + verbose=0, + retrain_full=False, + ) + + np.testing.assert_array_equal(automl.model.classes_, present_classes) + np.testing.assert_array_equal(automl.classes_, labels) + features = automl.preprocess(X_val) + raw = automl.model.predict_proba(features) + probabilities = automl.predict_proba(X_val) + assert probabilities.shape == (len(y_val), 3) + np.testing.assert_array_equal(probabilities[:, present_classes], raw) + np.testing.assert_array_equal(probabilities[:, missing_class], 0) + np.testing.assert_allclose(probabilities.sum(axis=1), 1) + assert log_loss(labels[y_val], probabilities, labels=automl.classes_) == pytest.approx(automl.best_loss) + np.testing.assert_array_equal(automl.model.predict_proba(features), raw) @pytest.mark.parametrize( From 57e6f84e8c91f53a297f21e424bc1a5bb239f6be Mon Sep 17 00:00:00 2001 From: AryanRG Date: Tue, 27 Oct 2026 00:26:08 +0530 Subject: [PATCH 06/14] Align binary sample probabilities and preserve non-finite output --- flaml/automl/automl.py | 9 +- flaml/automl/ml.py | 13 +-- test/automl/test_holdout_labels.py | 128 +++++++++++++++++++++++++---- 3 files changed, 128 insertions(+), 22 deletions(-) diff --git a/flaml/automl/automl.py b/flaml/automl/automl.py index 5fabcc322e..496b4453c3 100644 --- a/flaml/automl/automl.py +++ b/flaml/automl/automl.py @@ -905,7 +905,14 @@ def predict_proba(self, X, **pred_kwargs): Returns: A numpy array of shape n * c. c is the # classes. Each element at - (i, j) is the probability for instance i to be in class j. + (i, j) is the probability for instance i to be in class `classes_[j]`. + For tabular classification, classes absent from a retained sampled model + receive zero probability. A single-class LightGBM or XGBoost sample is + normalized over its observed class; non-finite backend rows remain + non-finite. These aligned probabilities can therefore differ from the + raw output of `automl.model.predict_proba(automl.preprocess(X))`. + Requested raw scores, leaf indices and feature contributions are returned + unchanged from the backend instead of being aligned as probabilities. """ estimator = getattr(self, "_trained_estimator", None) if estimator is None: diff --git a/flaml/automl/ml.py b/flaml/automl/ml.py index 353be8ad5a..9f4f3a700d 100644 --- a/flaml/automl/ml.py +++ b/flaml/automl/ml.py @@ -602,25 +602,28 @@ def default_cv_score_agg_func(val_loss_folds, log_metrics_folds): def _align_log_loss_probabilities(predictions, estimator, labels): - """Match sampled classifiers' probability columns to log_loss's label order.""" + """Match sampled classifiers' probability columns to sorted label order.""" if labels is None or isinstance(predictions, (psDataFrame, psSeries)): return predictions classes = getattr(estimator, "classes_", None) probabilities = np.asarray(predictions) if classes is None or probabilities.ndim != 2: return predictions - # For multiclass scoring, these binary APIs can emit an implicit second class. - # Normalize over the sole observed class; binary scoring keeps both columns. + # These binary APIs can emit an implicit second class even for a one-class fit. + # Normalize over the sole observed class before aligning binary or multiclass labels. if ( len(classes) == 1 and probabilities.shape[1] == 2 - and len(np.unique(labels)) > 2 + and len(np.unique(labels)) > 1 and ( isinstance(getattr(estimator, "model", estimator), XGBClassifier) or (LGBMClassifier is not None and isinstance(getattr(estimator, "model", estimator), LGBMClassifier)) ) ): - probabilities = np.ones_like(probabilities[:, :1]) + # Invalid backend rows must not become confident finite predictions. + probabilities = np.where( + np.isfinite(probabilities).all(axis=1, keepdims=True), np.ones_like(probabilities[:, :1]), np.nan + ) if probabilities.shape[1] != len(classes): return predictions # sklearn's log_loss sorts labels, even when an explicit override is unsorted. diff --git a/test/automl/test_holdout_labels.py b/test/automl/test_holdout_labels.py index 97180b8a66..cfd125aa49 100644 --- a/test/automl/test_holdout_labels.py +++ b/test/automl/test_holdout_labels.py @@ -8,6 +8,7 @@ from flaml import AutoML from flaml.automl import ml from flaml.automl.model import LGBMEstimator, LRL1Classifier +from flaml.automl.state import AutoMLState SETTINGS = { "task": "classification", @@ -54,20 +55,29 @@ def test_time_split_with_class_absent_from_latest_rows(): @pytest.mark.parametrize("skip_transform", [False, True]) @pytest.mark.parametrize("retrain_full", [False, True]) -def test_public_probabilities_with_complete_class_set(skip_transform, retrain_full): +def test_public_probabilities_with_complete_class_set(monkeypatch, skip_transform, retrain_full): X, y = _three_class_data() + retrained_sizes = [] + original = AutoMLState._train_with_config + + def recording(self, estimator, config, sample_size=None, is_retrain=False): + if is_retrain: + retrained_sizes.append(sample_size) + return original(self, estimator, config, sample_size, is_retrain) + + monkeypatch.setattr(AutoMLState, "_train_with_config", recording) automl = AutoML() automl.fit( - X[:180], - y[:180], - X_val=X[180:], - y_val=y[180:], + X, + y, + eval_method="holdout", metric="log_loss", sample=False, skip_transform=skip_transform, **{**SETTINGS, "retrain_full": retrain_full}, ) + assert retrained_sizes == ([len(X)] if retrain_full else []) raw = automl.model.predict_proba(automl.preprocess(X[180:])) np.testing.assert_array_equal(automl.predict_proba(X[180:]), raw) np.testing.assert_array_equal(automl.classes_, [0, 1, 2]) @@ -288,11 +298,8 @@ def recording(config, estimator, X_train, y_train, X_val, y_val, *args, **kwargs for features, target, actual in cases: raw = estimator.predict_proba(features) assert raw.shape == (len(target), 2) - if num_classes == 2: - expected = raw - else: - expected = np.zeros((len(target), num_classes), dtype=raw.dtype) - expected[:, 0] = 1.0 + expected = np.zeros((len(target), num_classes), dtype=raw.dtype) + expected[:, 0] = 1.0 assert np.isfinite(actual) assert actual == pytest.approx(log_loss(target, expected, labels=np.arange(num_classes))) return result @@ -327,15 +334,88 @@ def recording(config, estimator, X_train, y_train, X_val, y_val, *args, **kwargs assert probabilities.shape == (len(y_val), num_classes) np.testing.assert_array_equal(automl.classes_, labels) np.testing.assert_allclose(probabilities.sum(axis=1), 1) - if num_classes == 2: - np.testing.assert_array_equal(probabilities, raw) - else: - np.testing.assert_array_equal(probabilities[:, 0], 1) - np.testing.assert_array_equal(probabilities[:, 1:], 0) + np.testing.assert_array_equal(probabilities[:, 0], 1) + np.testing.assert_array_equal(probabilities[:, 1:], 0) assert log_loss(labels[y_val], probabilities, labels=automl.classes_) == pytest.approx(automl.best_loss) np.testing.assert_array_equal(automl.model.predict_proba(automl.preprocess(X_val)), raw) +def test_single_class_binary_lightgbm_public_class_axis(): + rng = np.random.RandomState(81) + y = np.full(3000, 20) + y[[1500, 2500]] = 10 + X = rng.randn(len(y), 4) + X_val = rng.randn(300, 4) + y_val = np.where(np.arange(len(X_val)) % 5 == 0, 10, 20) + automl = AutoML() + automl.fit( + X, + y, + X_val=X_val, + y_val=y_val, + task="classification", + metric="log_loss", + log_training_metric=True, + estimator_list=["lgbm"], + max_iter=2, + seed=1, + min_sample_size=50, + sample=True, + starting_points={}, + auto_augment=False, + n_jobs=1, + verbose=0, + retrain_full=False, + ) + np.testing.assert_array_equal(automl.model.classes_, [1]) + np.testing.assert_array_equal(automl.classes_, [10, 20]) + predictions = automl.predict(X_val) + np.testing.assert_array_equal(predictions, 20) + probabilities = automl.predict_proba(X_val) + np.testing.assert_array_equal(probabilities, np.tile([0.0, 1.0], (len(X_val), 1))) + np.testing.assert_array_equal(automl.classes_[probabilities.argmax(axis=1)], predictions) + assert log_loss(y_val, probabilities, labels=automl.classes_) == pytest.approx(automl.best_loss) + + +@pytest.mark.parametrize("learner", ["xgboost", "xgb_limitdepth"]) +def test_single_class_xgboost_public_probabilities_preserve_nan(learner): + rng = np.random.RandomState(81) + y = np.zeros(3000, dtype=int) + y[1500], y[2500] = 1, 2 + X = rng.randn(len(y), 4) + X_val = rng.randn(300, 4) + automl = AutoML() + automl.fit( + X, + y, + X_val=X_val, + y_val=np.arange(len(X_val)) % 2, + task="classification", + metric="log_loss", + estimator_list=[learner], + max_iter=2, + seed=1, + min_sample_size=50, + sample=True, + starting_points={}, + auto_augment=False, + n_jobs=1, + verbose=0, + retrain_full=False, + ) + np.testing.assert_array_equal(automl.model.classes_, [0]) + base_margin = np.zeros(len(X_val)) + base_margin[::2] = np.nan + raw = automl.model.predict_proba(automl.preprocess(X_val), base_margin=base_margin) + assert np.isnan(raw[::2]).all() + assert np.isfinite(raw[1::2]).all() + probabilities = automl.predict_proba(X_val, base_margin=base_margin) + assert probabilities.shape == (len(X_val), 3) + assert np.isnan(probabilities[::2, 0]).all() + np.testing.assert_array_equal(probabilities[:, 1:], 0) + np.testing.assert_array_equal(probabilities[1::2, 0], 1) + + @pytest.mark.parametrize("output", ["raw_score", "pred_leaf", "pred_contrib", None]) def test_sampled_lightgbm_prediction_options(output): rng = np.random.RandomState(81) @@ -426,7 +506,7 @@ def test_public_probabilities_from_sampled_classifier(missing_class, learner): @pytest.mark.parametrize( "sole_class, labels", - [(0, [0, 1, 2]), (1, [2, 1, 0]), (7, [1, 7, 3]), ("b", ["c", "b", "a"])], + [(0, [0, 1]), (1, [0, 1]), (0, [0, 1, 2]), (1, [2, 1, 0]), (7, [1, 7, 3]), ("b", ["c", "b", "a"])], ) @pytest.mark.parametrize("wrapped", [False, True]) def test_single_class_lightgbm_probability_alignment(sole_class, labels, wrapped): @@ -459,6 +539,22 @@ def test_single_class_xgboost_probability_alignment(wrapped): np.testing.assert_array_equal(raw, before) +@pytest.mark.parametrize("invalid", [np.nan, np.inf, -np.inf]) +@pytest.mark.parametrize("labels", [[0, 1], [0, 1, 2]]) +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_single_class_probability_alignment_preserves_nonfinite_rows(invalid, labels, dtype): + estimator = SimpleNamespace(model=ml.LGBMClassifier(), classes_=np.array([1])) + raw = np.array([[0.8, 0.2], [0.5, invalid], [invalid, 0.5]], dtype=dtype) + before = raw.copy() + actual = ml._align_log_loss_probabilities(raw, estimator, labels) + assert actual.dtype == raw.dtype + assert actual.shape == (3, len(labels)) + assert actual[0, 1] == 1 + assert np.isnan(actual[1:, 1]).all() + np.testing.assert_array_equal(actual[:, np.array(labels) != 1], 0) + np.testing.assert_array_equal(raw, before) + + def test_unknown_single_class_estimator_keeps_unexpected_probability_width(): raw = np.array([[0.2, 0.8]]) estimator = SimpleNamespace(classes_=np.array([0])) From 8a7619ff03aba79d8838da1d891256c3fb6e3555 Mon Sep 17 00:00:00 2001 From: AryanRG Date: Tue, 27 Oct 2026 13:37:09 +0530 Subject: [PATCH 07/14] Preserve native class axes for sampled classifiers --- flaml/automl/automl.py | 32 +++-- test/automl/test_holdout_labels.py | 213 +++++++++++++++++++++++++++-- 2 files changed, 223 insertions(+), 22 deletions(-) diff --git a/flaml/automl/automl.py b/flaml/automl/automl.py index 496b4453c3..9d9df703d6 100644 --- a/flaml/automl/automl.py +++ b/flaml/automl/automl.py @@ -800,10 +800,13 @@ def label_transformer(self): @property def classes_(self): - """A numpy array of shape (n_classes,) for class labels.""" + """A numpy array of full training class labels, including for sparse or untransformed inputs.""" attr = getattr(self, "_label_transformer", None) if attr: return attr.classes_ + classes = getattr(self, "_classes", None) + if classes is not None: + return classes attr = getattr(self, "_trained_estimator", None) if attr: return attr.classes_ @@ -907,7 +910,8 @@ def predict_proba(self, X, **pred_kwargs): A numpy array of shape n * c. c is the # classes. Each element at (i, j) is the probability for instance i to be in class `classes_[j]`. For tabular classification, classes absent from a retained sampled model - receive zero probability. A single-class LightGBM or XGBoost sample is + receive zero probability, including with sparse inputs or disabled + preprocessing. A single-class LightGBM or XGBoost sample is normalized over its observed class; non-finite backend rows remain non-finite. These aligned probabilities can therefore differ from the raw output of `automl.model.predict_proba(automl.preprocess(X))`. @@ -920,14 +924,12 @@ def predict_proba(self, X, **pred_kwargs): return None X = self._state.task.preprocess(X, self._transformer) proba = self._trained_estimator.predict_proba(X, **pred_kwargs) - if ( - self._state.task.name in ("classification", "binary", "multiclass") - and self._label_transformer - and not any(pred_kwargs.get(option) for option in ("raw_score", "pred_leaf", "pred_contrib")) + if self._state.task.name in ("classification", "binary", "multiclass") and not any( + pred_kwargs.get(option) for option in ("raw_score", "pred_leaf", "pred_contrib") ): - # The estimator uses encoded labels; public columns follow classes_. + # Match the estimator's encoded or native labels to the full class set. # Raw scores, leaf indices and feature contributions are not probabilities. - labels = np.arange(len(self._label_transformer.classes_)) + labels = np.arange(len(self.classes_)) if self._label_transformer else self.classes_ proba = _align_log_loss_probabilities(proba, estimator, labels) return proba @@ -1864,6 +1866,7 @@ def metric_constraints(self) -> list: def _prepare_data(self, eval_method, split_ratio, n_splits): # Reset on every fit, including when the same AutoML changes tasks. self._state.holdout_labels = None + self._classes = None self._state.task.prepare_data( self._state, self._X_train_all, @@ -1877,15 +1880,24 @@ def _prepare_data(self, eval_method, split_ratio, n_splits): self._sample_weight_full, self._allow_label_overlap, ) + native_class_axis = ( + self._state.task.name in ("classification", "binary", "multiclass") + and not self._label_transformer + and not isinstance(self._state.y_train_all, psSeries) + ) if ( - eval_method == "holdout" + (eval_method == "holdout" or native_class_axis) and self._state.task.is_classification() and not self._state.task.is_token_classification() and self._state.y_train_all is not None ): _, labels = len_labels(self._state.y_train_all, return_labels=True) # Do not retain a live pandas-on-Spark object in serialized state. - self._state.holdout_labels = labels.to_numpy() if isinstance(labels, psSeries) else labels + labels = labels.to_numpy() if isinstance(labels, psSeries) else labels + if eval_method == "holdout": + self._state.holdout_labels = labels + if native_class_axis: + self._classes = labels self.data_size_full = self._state.data_size_full def fit( diff --git a/test/automl/test_holdout_labels.py b/test/automl/test_holdout_labels.py index cfd125aa49..b320b53006 100644 --- a/test/automl/test_holdout_labels.py +++ b/test/automl/test_holdout_labels.py @@ -2,6 +2,7 @@ import numpy as np import pytest +from scipy.sparse import csr_matrix, issparse from sklearn.metrics import f1_score, log_loss from xgboost import XGBClassifier @@ -53,10 +54,14 @@ def test_time_split_with_class_absent_from_latest_rows(): assert np.isfinite(automl.best_loss) -@pytest.mark.parametrize("skip_transform", [False, True]) +@pytest.mark.parametrize("input_mode", ["transform", "skip", "sparse"]) @pytest.mark.parametrize("retrain_full", [False, True]) -def test_public_probabilities_with_complete_class_set(monkeypatch, skip_transform, retrain_full): +def test_public_probabilities_with_complete_class_set(monkeypatch, input_mode, retrain_full): X, y = _three_class_data() + if input_mode != "transform": + y = 10 * (y + 1) + if input_mode == "sparse": + X = csr_matrix(X) retrained_sizes = [] original = AutoMLState._train_with_config @@ -73,14 +78,14 @@ def recording(self, estimator, config, sample_size=None, is_retrain=False): eval_method="holdout", metric="log_loss", sample=False, - skip_transform=skip_transform, + skip_transform=input_mode == "skip", **{**SETTINGS, "retrain_full": retrain_full}, ) - assert retrained_sizes == ([len(X)] if retrain_full else []) + assert retrained_sizes == ([X.shape[0]] if retrain_full else []) raw = automl.model.predict_proba(automl.preprocess(X[180:])) np.testing.assert_array_equal(automl.predict_proba(X[180:]), raw) - np.testing.assert_array_equal(automl.classes_, [0, 1, 2]) + np.testing.assert_array_equal(automl.classes_, np.unique(y)) @pytest.mark.parametrize("eval_method", ["holdout", "cv"]) @@ -378,18 +383,21 @@ def test_single_class_binary_lightgbm_public_class_axis(): @pytest.mark.parametrize("learner", ["xgboost", "xgb_limitdepth"]) -def test_single_class_xgboost_public_probabilities_preserve_nan(learner): +@pytest.mark.parametrize("input_mode", ["transform", "skip", "sparse"]) +def test_single_class_xgboost_public_probabilities_preserve_nan(learner, input_mode): rng = np.random.RandomState(81) y = np.zeros(3000, dtype=int) y[1500], y[2500] = 1, 2 X = rng.randn(len(y), 4) X_val = rng.randn(300, 4) + if input_mode == "sparse": + X, X_val = csr_matrix(X), csr_matrix(X_val) automl = AutoML() automl.fit( X, y, X_val=X_val, - y_val=np.arange(len(X_val)) % 2, + y_val=np.arange(X_val.shape[0]) % 2, task="classification", metric="log_loss", estimator_list=[learner], @@ -402,34 +410,210 @@ def test_single_class_xgboost_public_probabilities_preserve_nan(learner): n_jobs=1, verbose=0, retrain_full=False, + skip_transform=input_mode == "skip", ) np.testing.assert_array_equal(automl.model.classes_, [0]) - base_margin = np.zeros(len(X_val)) + base_margin = np.zeros(X_val.shape[0]) base_margin[::2] = np.nan raw = automl.model.predict_proba(automl.preprocess(X_val), base_margin=base_margin) assert np.isnan(raw[::2]).all() assert np.isfinite(raw[1::2]).all() probabilities = automl.predict_proba(X_val, base_margin=base_margin) - assert probabilities.shape == (len(X_val), 3) + assert probabilities.shape == (X_val.shape[0], 3) assert np.isnan(probabilities[::2, 0]).all() np.testing.assert_array_equal(probabilities[:, 1:], 0) np.testing.assert_array_equal(probabilities[1::2, 0], 1) +@pytest.mark.parametrize("input_mode", ["skip", "sparse"]) +@pytest.mark.parametrize( + "learner, labels, sole_class", + [ + ("lgbm", [0, 1], 0), + ("lgbm", [0, 1], 1), + ("lgbm", [10, 20, 30], 20), + ("xgboost", [0, 1, 2], 0), + ("xgb_limitdepth", [0, 1, 2], 0), + ], +) +def test_native_single_class_sample_public_probabilities(monkeypatch, input_mode, learner, labels, sole_class): + rng = np.random.RandomState(81) + y = np.full(3000, sole_class) + other_classes = [label for label in labels if label != sole_class] + y[1500], y[2500] = other_classes[0], other_classes[-1] + X = rng.randn(len(y), 4) + X_val = rng.randn(300, 4) + y_val = np.resize(labels, len(X_val)) + if input_mode == "sparse": + X, X_val = csr_matrix(X), csr_matrix(X_val) + original = ml._eval_estimator + sampled_classes = [] + + def recording(config, estimator, X_train, y_train, X_val, y_val, *args, **kwargs): + result = original(config, estimator, X_train, y_train, X_val, y_val, *args, **kwargs) + sampled_classes.append(estimator.classes_.copy()) + for target, loss in [(y_val, result[0]), (y_train, result[1]["train_loss"])]: + expected = np.zeros((len(target), len(labels)), dtype=estimator.predict_proba(X_val).dtype) + expected[:, labels.index(sole_class)] = 1 + assert loss == pytest.approx(log_loss(target, expected, labels=labels)) + return result + + monkeypatch.setattr(ml, "_eval_estimator", recording) + automl = AutoML() + automl.fit( + X, + y, + X_val=X_val, + y_val=y_val, + task="classification", + metric="log_loss", + log_training_metric=True, + estimator_list=[learner], + max_iter=2, + seed=1, + min_sample_size=50, + sample=True, + starting_points={}, + auto_augment=False, + n_jobs=1, + verbose=0, + retrain_full=False, + skip_transform=input_mode == "skip", + ) + assert not automl.label_transformer + assert len(sampled_classes) == 2 + assert all(np.array_equal(classes, [sole_class]) for classes in sampled_classes) + np.testing.assert_array_equal(automl.classes_, labels) + raw = automl.model.predict_proba(automl.preprocess(X_val)) + assert raw.shape == (X_val.shape[0], 2) + probabilities = automl.predict_proba(X_val) + expected = np.zeros((X_val.shape[0], len(labels))) + expected[:, labels.index(sole_class)] = 1 + np.testing.assert_array_equal(probabilities, expected) + np.testing.assert_array_equal(automl.classes_[probabilities.argmax(axis=1)], automl.predict(X_val)) + assert log_loss(y_val, probabilities, labels=automl.classes_) == pytest.approx(automl.best_loss) + np.testing.assert_array_equal(automl.model.predict_proba(automl.preprocess(X_val)), raw) + + +@pytest.mark.parametrize("input_mode", ["skip", "sparse"]) +@pytest.mark.parametrize("missing_class", [10, 20, 30]) +def test_native_sampled_lightgbm_probability_columns(input_mode, missing_class): + rng = np.random.RandomState(1) + labels = np.array([10, 20, 30]) + present_classes = labels[labels != missing_class] + y = rng.choice(present_classes, size=3000) + y[rng.choice(len(y), 40, replace=False)] = missing_class + X = rng.randn(len(y), 4) + X_val = rng.randn(300, 4) + y_val = np.resize(labels, len(X_val)) + if input_mode == "sparse": + X, X_val = csr_matrix(X), csr_matrix(X_val) + automl = AutoML() + automl.fit( + X, + y, + X_val=X_val, + y_val=y_val, + task="classification", + metric="log_loss", + estimator_list=["lgbm"], + max_iter=2, + seed=1, + min_sample_size=50, + sample=True, + starting_points={}, + auto_augment=False, + n_jobs=1, + verbose=0, + retrain_full=False, + skip_transform=input_mode == "skip", + ) + np.testing.assert_array_equal(automl.model.classes_, present_classes) + np.testing.assert_array_equal(automl.classes_, labels) + raw = automl.model.predict_proba(automl.preprocess(X_val)) + probabilities = automl.predict_proba(X_val) + np.testing.assert_array_equal(probabilities[:, labels != missing_class], raw) + np.testing.assert_array_equal(probabilities[:, labels == missing_class], 0) + assert log_loss(y_val, probabilities, labels=automl.classes_) == pytest.approx(automl.best_loss) + + +@pytest.mark.parametrize("input_mode", ["skip", "sparse"]) +@pytest.mark.parametrize("eval_method", ["holdout", "cv"]) +def test_native_class_axis_does_not_change_callable_metric_labels(input_mode, eval_method): + X, y = _three_class_data() + y = 10 * (y + 1) + if input_mode == "sparse": + X = csr_matrix(X) + received = [] + + def custom_metric(X_val, y_val, estimator, labels, *args, **kwargs): + received.append(labels) + return 0.5, {} + + automl = AutoML() + automl.fit( + X, + y, + metric=custom_metric, + eval_method=eval_method, + n_splits=3, + skip_transform=input_mode == "skip", + **SETTINGS, + ) + assert received + if eval_method == "holdout": + assert all(labels is None for labels in received) + else: + assert all(np.array_equal(labels, [10, 20, 30]) for labels in received) + np.testing.assert_array_equal(automl.classes_, [10, 20, 30]) + np.testing.assert_array_equal(automl.predict_proba(X), automl.model.predict_proba(automl.preprocess(X))) + + +@pytest.mark.parametrize("input_mode", ["skip", "sparse"]) +def test_native_class_axis_refreshed_when_refitting(input_mode): + X, y = _three_class_data() + if input_mode == "sparse": + X = csr_matrix(X) + automl = AutoML() + for current_y in (10 * (y + 1), (y % 2) + 5): + automl.fit(X, current_y, metric="log_loss", skip_transform=input_mode == "skip", **SETTINGS) + np.testing.assert_array_equal(automl.classes_, np.unique(current_y)) + np.testing.assert_array_equal(automl.predict_proba(X), automl.model.predict_proba(automl.preprocess(X))) + automl.fit( + X, + y.astype(float), + task="regression", + estimator_list=["lgbm"], + max_iter=1, + n_jobs=1, + verbose=0, + skip_transform=input_mode == "skip", + ) + assert automl._classes is None + # Returning to transformed classification must not reuse native labels. + X, y = _three_class_data() + automl.fit(X, y, task="classification", skip_transform=False, **{k: v for k, v in SETTINGS.items() if k != "task"}) + assert automl._classes is None + np.testing.assert_array_equal(automl.classes_, [0, 1, 2]) + + @pytest.mark.parametrize("output", ["raw_score", "pred_leaf", "pred_contrib", None]) -def test_sampled_lightgbm_prediction_options(output): +@pytest.mark.parametrize("input_mode", ["transform", "skip", "sparse"]) +def test_sampled_lightgbm_prediction_options(output, input_mode): rng = np.random.RandomState(81) y = np.zeros(3000, dtype=int) y[1500], y[2500] = 1, 2 # One feature makes contribution scores have the same width as binary probabilities. X = rng.randn(len(y), 1) X_val = rng.randn(300, 1) + if input_mode == "sparse": + X, X_val = csr_matrix(X), csr_matrix(X_val) automl = AutoML() automl.fit( X, y, X_val=X_val, - y_val=np.arange(len(X_val)) % 2, + y_val=np.arange(X_val.shape[0]) % 2, task="classification", metric="log_loss", estimator_list=["lgbm"], @@ -442,6 +626,7 @@ def test_sampled_lightgbm_prediction_options(output): n_jobs=1, verbose=0, retrain_full=False, + skip_transform=input_mode == "skip", ) np.testing.assert_array_equal(automl.model.classes_, [0]) kwargs = {"num_iteration": 2} @@ -450,9 +635,13 @@ def test_sampled_lightgbm_prediction_options(output): raw = automl.model.predict_proba(automl.preprocess(X_val), **kwargs) actual = automl.predict_proba(X_val, **kwargs) if output is None: - assert actual.shape == (len(X_val), len(automl.classes_)) + assert actual.shape == (X_val.shape[0], len(automl.classes_)) np.testing.assert_array_equal(actual[:, 0], 1) np.testing.assert_array_equal(actual[:, 1:], 0) + elif issparse(raw): + assert issparse(actual) + assert actual.shape == raw.shape + assert (actual != raw).nnz == 0 else: np.testing.assert_array_equal(actual, raw) From 592085573a760c9d8ba83f170c5d6043f6633678 Mon Sep 17 00:00:00 2001 From: AryanRG Date: Tue, 27 Oct 2026 18:34:46 +0530 Subject: [PATCH 08/14] Preserve native class alignment after rejected refits --- flaml/automl/automl.py | 29 +++-- test/automl/test_holdout_labels.py | 171 ++++++++++++++++++++++++++++- 2 files changed, 190 insertions(+), 10 deletions(-) diff --git a/flaml/automl/automl.py b/flaml/automl/automl.py index 9d9df703d6..d369692f62 100644 --- a/flaml/automl/automl.py +++ b/flaml/automl/automl.py @@ -800,7 +800,11 @@ def label_transformer(self): @property def classes_(self): - """A numpy array of full training class labels, including for sparse or untransformed inputs.""" + """Class labels from the label transformer or estimator. + + For local tabular classification, includes the full training class set, + including for sparse or untransformed inputs. + """ attr = getattr(self, "_label_transformer", None) if attr: return attr.classes_ @@ -907,7 +911,8 @@ def predict_proba(self, X, **pred_kwargs): the searched learners, such as per_device_eval_batch_size. Returns: - A numpy array of shape n * c. c is the # classes. Each element at + For local tabular classification, a numpy array of shape n * c, + where c is the number of classes. Each element at (i, j) is the probability for instance i to be in class `classes_[j]`. For tabular classification, classes absent from a retained sampled model receive zero probability, including with sparse inputs or disabled @@ -917,6 +922,7 @@ def predict_proba(self, X, **pred_kwargs): raw output of `automl.model.predict_proba(automl.preprocess(X))`. Requested raw scores, leaf indices and feature contributions are returned unchanged from the backend instead of being aligned as probabilities. + Spark outputs are returned unchanged in their backend format. """ estimator = getattr(self, "_trained_estimator", None) if estimator is None: @@ -924,9 +930,14 @@ def predict_proba(self, X, **pred_kwargs): return None X = self._state.task.preprocess(X, self._transformer) proba = self._trained_estimator.predict_proba(X, **pred_kwargs) - if self._state.task.name in ("classification", "binary", "multiclass") and not any( - pred_kwargs.get(option) for option in ("raw_score", "pred_leaf", "pred_contrib") - ): + if isinstance(proba, (psDataFrame, psSeries)): + return proba + # A failed task change can leave the previous classifier installed. + # Keep its retained native class axis aligned until the model is replaced. + if ( + self._state.task.name in ("classification", "binary", "multiclass") + or getattr(self, "_classes", None) is not None + ) and not any(pred_kwargs.get(option) for option in ("raw_score", "pred_leaf", "pred_contrib")): # Match the estimator's encoded or native labels to the full class set. # Raw scores, leaf indices and feature contributions are not probabilities. labels = np.arange(len(self.classes_)) if self._label_transformer else self.classes_ @@ -1291,6 +1302,7 @@ def retrain_from_log( best_config, sample_size=sample_size, )[0] + self._classes = self._state.native_classes logger.info("retrain from log succeeded") return training_duration @@ -1866,7 +1878,7 @@ def metric_constraints(self) -> list: def _prepare_data(self, eval_method, split_ratio, n_splits): # Reset on every fit, including when the same AutoML changes tasks. self._state.holdout_labels = None - self._classes = None + self._state.native_classes = None self._state.task.prepare_data( self._state, self._X_train_all, @@ -1897,7 +1909,7 @@ def _prepare_data(self, eval_method, split_ratio, n_splits): if eval_method == "holdout": self._state.holdout_labels = labels if native_class_axis: - self._classes = labels + self._state.native_classes = labels self.data_size_full = self._state.data_size_full def fit( @@ -3317,6 +3329,9 @@ def _search(self): self._iter_per_learner_fullsize = {e: 0 for e in self.estimator_list} self._fullsize_reached = False self._trained_estimator = None + # Publish the prepared axis only once the previous model is discarded. + # Setup errors before search must not relabel the still-installed model. + self._classes = self._state.native_classes self._best_estimator = None self._retrained_config = {} self._warn_threshold = 10 diff --git a/test/automl/test_holdout_labels.py b/test/automl/test_holdout_labels.py index b320b53006..e9443b383a 100644 --- a/test/automl/test_holdout_labels.py +++ b/test/automl/test_holdout_labels.py @@ -8,8 +8,10 @@ from flaml import AutoML from flaml.automl import ml -from flaml.automl.model import LGBMEstimator, LRL1Classifier +from flaml.automl.model import BaseEstimator, LGBMEstimator, LRL1Classifier, SparkGBTEstimator, SparkNaiveBayesEstimator +from flaml.automl.spark import psDataFrame, psSeries from flaml.automl.state import AutoMLState +from flaml.automl.task.factory import task_factory SETTINGS = { "task": "classification", @@ -432,6 +434,7 @@ def test_single_class_xgboost_public_probabilities_preserve_nan(learner, input_m ("lgbm", [0, 1], 0), ("lgbm", [0, 1], 1), ("lgbm", [10, 20, 30], 20), + ("lgbm", ["a", "b", "c"], "b"), ("xgboost", [0, 1, 2], 0), ("xgb_limitdepth", [0, 1, 2], 0), ], @@ -570,13 +573,37 @@ def custom_metric(X_val, y_val, estimator, labels, *args, **kwargs): @pytest.mark.parametrize("input_mode", ["skip", "sparse"]) -def test_native_class_axis_refreshed_when_refitting(input_mode): +@pytest.mark.parametrize("eval_method", ["holdout", "cv"]) +@pytest.mark.parametrize("string_labels", [False, True]) +def test_native_class_axis_refreshed_when_refitting(monkeypatch, input_mode, eval_method, string_labels): X, y = _three_class_data() if input_mode == "sparse": X = csr_matrix(X) + from flaml.automl import automl as automl_module + + calls = [] + original = automl_module.len_labels + + def counting(values, *args, **kwargs): + calls.append(len(values)) + return original(values, *args, **kwargs) + + monkeypatch.setattr(automl_module, "len_labels", counting) automl = AutoML() for current_y in (10 * (y + 1), (y % 2) + 5): - automl.fit(X, current_y, metric="log_loss", skip_transform=input_mode == "skip", **SETTINGS) + if string_labels: + current_y = current_y.astype(str) + calls.clear() + automl.fit( + X, + current_y, + metric="log_loss", + eval_method=eval_method, + n_splits=3, + skip_transform=input_mode == "skip", + **SETTINGS, + ) + assert calls == [len(y)] np.testing.assert_array_equal(automl.classes_, np.unique(current_y)) np.testing.assert_array_equal(automl.predict_proba(X), automl.model.predict_proba(automl.preprocess(X))) automl.fit( @@ -597,6 +624,144 @@ def test_native_class_axis_refreshed_when_refitting(input_mode): np.testing.assert_array_equal(automl.classes_, [0, 1, 2]) +@pytest.mark.parametrize("input_mode", ["skip", "sparse"]) +@pytest.mark.parametrize("eval_method", ["holdout", "cv"]) +def test_rejected_native_refit_preserves_installed_class_axis(input_mode, eval_method): + X, y = _three_class_data(n=120) + if input_mode == "sparse": + X = csr_matrix(X) + settings = { + **SETTINGS, + "estimator_list": ["lgbm"], + "max_iter": 2, + "eval_method": eval_method, + "n_splits": 3, + "skip_transform": input_mode == "skip", + } + automl = AutoML() + automl.fit(X, y % 2, metric="log_loss", **settings) + installed = automl.model + classes = automl.classes_.copy() + probabilities = automl.predict_proba(X) + assert probabilities.shape == (120, 2) + + with pytest.raises(ValueError, match="only supports binary classification"): + automl.fit(X, 10 * (y + 1), metric="roc_auc", **settings) + + assert automl.model is installed + np.testing.assert_array_equal(automl.predict_proba(X), probabilities) + np.testing.assert_array_equal(automl.classes_, classes) + assert automl.predict_proba(X).shape[1] == len(automl.classes_) + + automl.fit(X, 10 * (y + 1), metric="log_loss", **settings) + assert automl.model is not installed + np.testing.assert_array_equal(automl.classes_, [10, 20, 30]) + assert automl.predict_proba(X).shape == (120, 3) + + +@pytest.mark.parametrize("input_mode", ["skip", "sparse"]) +def test_rejected_task_change_preserves_sampled_probability_axis(input_mode): + rng = np.random.RandomState(131) + X = rng.normal(size=(3000, 4)) + y = np.arange(len(X)) % 2 + y[-1] = 2 + X_val = rng.normal(size=(80, 4)) + if input_mode == "sparse": + X, X_val = csr_matrix(X), csr_matrix(X_val) + settings = dict( + estimator_list=["lgbm"], + n_jobs=1, + verbose=0, + max_iter=2, + auto_augment=False, + skip_transform=input_mode == "skip", + retrain_full=False, + ) + automl = AutoML() + automl.fit( + X, + y, + X_val=X_val, + y_val=np.arange(80) % 2, + task="classification", + metric="log_loss", + sample=True, + min_sample_size=50, + starting_points={}, + seed=1, + **settings, + ) + installed = automl.model + assert len(installed.classes_) == 2 + classes = automl.classes_.copy() + probabilities = automl.predict_proba(X_val) + assert probabilities.shape == (80, 3) + + with pytest.raises(ValueError, match="metric.*parameter"): + automl.fit(X, np.arange(3000, dtype=float), task="regression", metric=42, **settings) + + assert automl.model is installed + np.testing.assert_array_equal(automl.classes_, classes) + np.testing.assert_array_equal(automl.predict_proba(X_val), probabilities) + + +@pytest.mark.parametrize("estimator_class", [SparkNaiveBayesEstimator, SparkGBTEstimator]) +@pytest.mark.parametrize("return_all", [False, True]) +def test_spark_probability_facade_bypasses_missing_class_metadata(monkeypatch, estimator_class, return_all): + # Controlled public facade: no Spark training or native Spark runtime is required. + # Use repository Spark types without constructing a live Spark session. + output = object.__new__(psDataFrame if return_all else psSeries) + estimator = estimator_class.__new__(estimator_class) + BaseEstimator.__init__(estimator, task="binary") + estimator._model = SimpleNamespace() # Like these Spark models, has no classes_. + with pytest.raises(AttributeError): + _ = estimator.classes_ + + def predict_proba(X, **kwargs): + assert kwargs == {"return_all": return_all} + return output + + monkeypatch.setattr(estimator, "predict_proba", predict_proba) + automl = AutoML() + automl._state.task = task_factory("classification") + automl._transformer = automl._label_transformer = None + automl.preserve_checkpoint = True + automl._trained_estimator = estimator + assert automl.predict_proba(np.zeros((2, 3)), return_all=return_all) is output + + +@pytest.mark.parametrize("input_mode", ["skip", "sparse"]) +@pytest.mark.parametrize("eval_method", ["holdout", "cv"]) +def test_native_class_axis_retrain_from_log(tmp_path, input_mode, eval_method): + X, y = _three_class_data() + if input_mode == "sparse": + X = csr_matrix(X) + y = np.array(["a", "b", "c"])[y] + log_file = str(tmp_path / "native.log") + automl = AutoML() + settings = {**SETTINGS, "estimator_list": ["lgbm"], "max_iter": 2, "skip_transform": input_mode == "skip"} + automl.fit(X, y, metric="log_loss", eval_method=eval_method, n_splits=3, log_file_name=log_file, **settings) + + # Replaying on an existing AutoML must replace its old native class axis. + automl.fit(X, np.arange(len(y)) % 2, metric="log_loss", **settings) + automl.retrain_from_log( + log_file, + X_train=X, + y_train=y, + task="classification", + eval_method=eval_method, + n_splits=3, + train_full=True, + record_id=0, + n_jobs=1, + skip_transform=input_mode == "skip", + ) + np.testing.assert_array_equal(automl.classes_, ["a", "b", "c"]) + probabilities = automl.predict_proba(X) + assert probabilities.shape == (len(y), 3) + np.testing.assert_array_equal(probabilities, automl.model.predict_proba(automl.preprocess(X))) + + @pytest.mark.parametrize("output", ["raw_score", "pred_leaf", "pred_contrib", None]) @pytest.mark.parametrize("input_mode", ["transform", "skip", "sparse"]) def test_sampled_lightgbm_prediction_options(output, input_mode): From a36076dba938db49b01765c3733a50ab427410e7 Mon Sep 17 00:00:00 2001 From: AryanRG Date: Wed, 28 Oct 2026 03:11:08 +0530 Subject: [PATCH 09/14] Preserve legacy probability order and clear empty replay labels --- flaml/automl/automl.py | 5 +- flaml/automl/ml.py | 14 ++++-- test/automl/test_holdout_labels.py | 77 +++++++++++++++++++++++++++++- 3 files changed, 89 insertions(+), 7 deletions(-) diff --git a/flaml/automl/automl.py b/flaml/automl/automl.py index d369692f62..675a2f7176 100644 --- a/flaml/automl/automl.py +++ b/flaml/automl/automl.py @@ -20,7 +20,7 @@ from flaml import tune from flaml.automl.logger import logger, logger_formatter from flaml.automl.ml import ( - _align_log_loss_probabilities, + _align_class_probabilities, huggingface_metric_to_mode, sklearn_metric_name_set, spark_metric_name_dict, @@ -941,7 +941,7 @@ def predict_proba(self, X, **pred_kwargs): # Match the estimator's encoded or native labels to the full class set. # Raw scores, leaf indices and feature contributions are not probabilities. labels = np.arange(len(self.classes_)) if self._label_transformer else self.classes_ - proba = _align_log_loss_probabilities(proba, estimator, labels) + proba = _align_class_probabilities(proba, estimator, labels) return proba def preprocess( @@ -1253,6 +1253,7 @@ def retrain_from_log( from .model import BaseEstimator as Estimator self._trained_estimator = Estimator() + self._classes = None return training_duration if not best: return diff --git a/flaml/automl/ml.py b/flaml/automl/ml.py index 9f4f3a700d..9053fd85ed 100644 --- a/flaml/automl/ml.py +++ b/flaml/automl/ml.py @@ -601,8 +601,8 @@ def default_cv_score_agg_func(val_loss_folds, log_metrics_folds): return metric_to_minimize, metrics_to_log -def _align_log_loss_probabilities(predictions, estimator, labels): - """Match sampled classifiers' probability columns to sorted label order.""" +def _align_class_probabilities(predictions, estimator, labels): + """Match sampled classifiers' probability columns to the supplied label order.""" if labels is None or isinstance(predictions, (psDataFrame, psSeries)): return predictions classes = getattr(estimator, "classes_", None) @@ -626,8 +626,7 @@ def _align_log_loss_probabilities(predictions, estimator, labels): ) if probabilities.shape[1] != len(classes): return predictions - # sklearn's log_loss sorts labels, even when an explicit override is unsorted. - labels = np.unique(labels) + labels = np.asarray(labels) if np.array_equal(classes, labels): return predictions positions = {label: index for index, label in enumerate(labels)} @@ -638,6 +637,13 @@ def _align_log_loss_probabilities(predictions, estimator, labels): return aligned +def _align_log_loss_probabilities(predictions, estimator, labels): + """Align probability columns to sklearn log_loss's sorted label order.""" + if labels is None or isinstance(predictions, (psDataFrame, psSeries)): + return predictions + return _align_class_probabilities(predictions, estimator, np.unique(labels)) + + def _eval_estimator( config, estimator, diff --git a/test/automl/test_holdout_labels.py b/test/automl/test_holdout_labels.py index e9443b383a..74f5896310 100644 --- a/test/automl/test_holdout_labels.py +++ b/test/automl/test_holdout_labels.py @@ -1,3 +1,4 @@ +import pickle from types import SimpleNamespace import numpy as np @@ -8,7 +9,14 @@ from flaml import AutoML from flaml.automl import ml -from flaml.automl.model import BaseEstimator, LGBMEstimator, LRL1Classifier, SparkGBTEstimator, SparkNaiveBayesEstimator +from flaml.automl.model import ( + BaseEstimator, + LGBMEstimator, + LRL1Classifier, + RandomForestEstimator, + SparkGBTEstimator, + SparkNaiveBayesEstimator, +) from flaml.automl.spark import psDataFrame, psSeries from flaml.automl.state import AutoMLState from flaml.automl.task.factory import task_factory @@ -31,6 +39,73 @@ def _three_class_data(n=240, seed=0): return X, y +class ReversedRandomForestEstimator(RandomForestEstimator): + @property + def classes_(self): + return super().classes_[::-1] + + def predict_proba(self, X, **kwargs): + return super().predict_proba(X, **kwargs)[:, ::-1] + + +@pytest.mark.parametrize("input_mode", ["skip", "sparse"]) +@pytest.mark.parametrize("labels", [[10, 20], ["a", "z"]]) +def test_legacy_pickle_preserves_custom_class_order(input_mode, labels): + X, y = _three_class_data(n=120) + y = np.asarray(labels)[y % 2] + if input_mode == "sparse": + X = csr_matrix(X) + automl = AutoML() + automl.add_learner("reversed_rf", ReversedRandomForestEstimator) + automl.fit( + X, + y, + task="classification", + estimator_list=["reversed_rf"], + max_iter=1, + n_jobs=1, + verbose=0, + metric="accuracy", + skip_transform=input_mode == "skip", + ) + # Older serialized AutoML objects have no cached native class axis. + del automl._classes + restored = pickle.loads(pickle.dumps(automl)) + expected_classes = np.asarray(labels)[::-1] + raw = restored.model.predict_proba(restored.preprocess(X)) + + np.testing.assert_array_equal(restored.classes_, expected_classes) + np.testing.assert_array_equal(restored.predict_proba(X), raw) + np.testing.assert_array_equal(restored.classes_[raw.argmax(axis=1)], restored.predict(X)) + + +@pytest.mark.parametrize("input_mode", ["skip", "sparse"]) +def test_empty_log_replay_clears_native_class_axis(tmp_path, input_mode): + X, y = _three_class_data(n=120) + y = 10 * (y + 1) + if input_mode == "sparse": + X = csr_matrix(X) + log_file = str(tmp_path / "native.log") + automl = AutoML() + automl.fit(X, y, log_file_name=log_file, skip_transform=input_mode == "skip", **SETTINGS) + np.testing.assert_array_equal(automl.classes_, [10, 20, 30]) + duration = automl.retrain_from_log( + log_file, + X_train=X, + y_train=y, + task="classification", + time_budget=0, + n_jobs=1, + skip_transform=input_mode == "skip", + ) + + assert duration == 0 + assert automl.model.model is None + assert automl._classes is None + with pytest.raises(AttributeError, match="classes_"): + _ = automl.classes_ + + def test_log_loss_with_validation_set_missing_a_class(): X, y = _three_class_data() X_train, y_train = X[:180], y[:180] From f988351954bb79f59d90057b3b8399aef6a6aa29 Mon Sep 17 00:00:00 2001 From: Aryan Rajesh Ganjoo <51299383+AryanRG@users.noreply.github.com> Date: Fri, 6 Nov 2026 15:50:21 +0530 Subject: [PATCH 10/14] Restore installed preprocessing after rejected refits --- flaml/automl/automl.py | 23 ++++++- test/automl/test_holdout_labels.py | 97 ++++++++++++++++++++++++++++++ 2 files changed, 119 insertions(+), 1 deletion(-) diff --git a/flaml/automl/automl.py b/flaml/automl/automl.py index d8482b7e16..338be58af9 100644 --- a/flaml/automl/automl.py +++ b/flaml/automl/automl.py @@ -12,7 +12,7 @@ import sys import time from concurrent.futures import as_completed -from functools import partial +from functools import partial, wraps from typing import Callable, List, Optional, Union import numpy as np @@ -94,6 +94,25 @@ def size(learner_classes: dict, config: dict) -> float: return learner_class.size(config) +def _keep_installed_preprocessing(fit): + """Restore the installed model's preprocessing if a fit fails before replacing it.""" + + @wraps(fit) + def wrapper(self, *args, **kwargs): + installed = getattr(self, "_trained_estimator", None) + names = ("_transformer", "_label_transformer", "_classes") + preprocessing = [getattr(self, name, None) for name in names] + try: + return fit(self, *args, **kwargs) + except BaseException: + if installed is not None and getattr(self, "_trained_estimator", None) is installed: + for name, value in zip(names, preprocessing): + setattr(self, name, value) + raise + + return wrapper + + # metrics that sklearn only computes for binary targets BINARY_ONLY_METRICS = ("roc_auc", "roc_auc_weighted", "ap", "f1") @@ -1044,6 +1063,7 @@ def get_estimator_from_log(self, log_file_name: str, record_id: int, task: str | ) return estimator + @_keep_installed_preprocessing def retrain_from_log( self, log_file_name, @@ -1918,6 +1938,7 @@ def _prepare_data(self, eval_method, split_ratio, n_splits): self._state.native_classes = labels self.data_size_full = self._state.data_size_full + @_keep_installed_preprocessing def fit( self, X_train=None, diff --git a/test/automl/test_holdout_labels.py b/test/automl/test_holdout_labels.py index 74f5896310..5cf1c6cce1 100644 --- a/test/automl/test_holdout_labels.py +++ b/test/automl/test_holdout_labels.py @@ -780,6 +780,103 @@ def test_rejected_task_change_preserves_sampled_probability_axis(input_mode): np.testing.assert_array_equal(automl.predict_proba(X_val), probabilities) +@pytest.mark.parametrize("skip_transform", [True, False]) +def test_rejected_refit_with_new_preprocessing_mode_preserves_installed_model(skip_transform): + rng = np.random.RandomState(131) + X = rng.normal(size=(3000, 4)) + y = np.arange(len(X)) % 2 + y[-1] = 2 + X_val = rng.normal(size=(80, 4)) + settings = dict( + task="classification", + estimator_list=["lgbm"], + n_jobs=1, + verbose=0, + max_iter=2, + auto_augment=False, + retrain_full=False, + ) + automl = AutoML() + automl.fit( + X, + y, + X_val=X_val, + y_val=np.arange(80) % 2, + metric="log_loss", + sample=True, + min_sample_size=50, + starting_points={}, + seed=1, + skip_transform=skip_transform, + **settings, + ) + installed = automl.model + assert len(installed.classes_) == 2 + np.testing.assert_array_equal(automl.classes_, [0, 1, 2]) + preprocessing = automl._transformer, automl._label_transformer + probabilities = automl.predict_proba(X_val) + predictions = automl.predict(X_val) + assert probabilities.shape == (80, 3) + + with pytest.raises(ValueError, match="metric.*parameter"): + automl.fit(X, 10 + 10 * (np.arange(3000) % 2), metric=42, skip_transform=not skip_transform, **settings) + + assert automl.model is installed + assert automl._transformer is preprocessing[0] + assert automl._label_transformer is preprocessing[1] + np.testing.assert_array_equal(automl.classes_, [0, 1, 2]) + np.testing.assert_array_equal(automl.predict_proba(X_val), probabilities) + np.testing.assert_array_equal(automl.predict(X_val), predictions) + + +@pytest.mark.parametrize("skip_transform", [True, False]) +def test_failed_retrain_from_log_preserves_installed_model(tmp_path, skip_transform): + rng = np.random.RandomState(131) + X = rng.normal(size=(3000, 4)) + y = np.arange(len(X)) % 2 + y[-1] = 2 + X_val = rng.normal(size=(80, 4)) + automl = AutoML() + automl.fit( + X, + y, + X_val=X_val, + y_val=np.arange(80) % 2, + task="classification", + estimator_list=["lgbm"], + metric="log_loss", + n_jobs=1, + verbose=0, + max_iter=2, + auto_augment=False, + retrain_full=False, + sample=True, + min_sample_size=50, + starting_points={}, + seed=1, + skip_transform=skip_transform, + ) + installed = automl.model + preprocessing = automl._transformer, automl._label_transformer + probabilities = automl.predict_proba(X_val) + assert probabilities.shape == (80, 3) + + with pytest.raises(FileNotFoundError): + automl.retrain_from_log( + str(tmp_path / "missing.log"), + X, + 10 + 10 * (np.arange(3000) % 2), + task="classification", + skip_transform=not skip_transform, + ) + + assert automl.model is installed + assert automl._transformer is preprocessing[0] + assert automl._label_transformer is preprocessing[1] + np.testing.assert_array_equal(automl.classes_, [0, 1, 2]) + np.testing.assert_array_equal(automl.predict_proba(X_val), probabilities) + + @pytest.mark.parametrize("estimator_class", [SparkNaiveBayesEstimator, SparkGBTEstimator]) @pytest.mark.parametrize("return_all", [False, True]) def test_spark_probability_facade_bypasses_missing_class_metadata(monkeypatch, estimator_class, return_all): From 30e3c72debcdab2045995eef48fbd0b237455682 Mon Sep 17 00:00:00 2001 From: Aryan Rajesh Ganjoo <51299383+AryanRG@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:54:21 +0530 Subject: [PATCH 11/14] Restore the installed task after rejected refits --- flaml/automl/automl.py | 8 ++++++-- test/automl/test_holdout_labels.py | 25 +++++++++++++++++++------ 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/flaml/automl/automl.py b/flaml/automl/automl.py index 338be58af9..7c4e9181ce 100644 --- a/flaml/automl/automl.py +++ b/flaml/automl/automl.py @@ -95,19 +95,23 @@ def size(learner_classes: dict, config: dict) -> float: def _keep_installed_preprocessing(fit): - """Restore the installed model's preprocessing if a fit fails before replacing it.""" + """Restore the installed model's task and preprocessing if a fit fails before replacing it.""" @wraps(fit) def wrapper(self, *args, **kwargs): installed = getattr(self, "_trained_estimator", None) - names = ("_transformer", "_label_transformer", "_classes") + names = ("_transformer", "_label_transformer", "_classes", "_estimator_type") preprocessing = [getattr(self, name, None) for name in names] + state = getattr(self, "_state", None) + task = getattr(state, "task", None) try: return fit(self, *args, **kwargs) except BaseException: if installed is not None and getattr(self, "_trained_estimator", None) is installed: for name, value in zip(names, preprocessing): setattr(self, name, value) + if state is not None: + state.task = task raise return wrapper diff --git a/test/automl/test_holdout_labels.py b/test/automl/test_holdout_labels.py index 5cf1c6cce1..ebd5944e28 100644 --- a/test/automl/test_holdout_labels.py +++ b/test/automl/test_holdout_labels.py @@ -734,7 +734,7 @@ def test_rejected_native_refit_preserves_installed_class_axis(input_mode, eval_m assert automl.predict_proba(X).shape == (120, 3) -@pytest.mark.parametrize("input_mode", ["skip", "sparse"]) +@pytest.mark.parametrize("input_mode", ["skip", "sparse", "transform"]) def test_rejected_task_change_preserves_sampled_probability_axis(input_mode): rng = np.random.RandomState(131) X = rng.normal(size=(3000, 4)) @@ -770,14 +770,18 @@ def test_rejected_task_change_preserves_sampled_probability_axis(input_mode): assert len(installed.classes_) == 2 classes = automl.classes_.copy() probabilities = automl.predict_proba(X_val) + predictions = automl.predict(X_val) assert probabilities.shape == (80, 3) with pytest.raises(ValueError, match="metric.*parameter"): automl.fit(X, np.arange(3000, dtype=float), task="regression", metric=42, **settings) assert automl.model is installed + assert automl._state.task.name == "multiclass" + assert automl._estimator_type == "classifier" np.testing.assert_array_equal(automl.classes_, classes) np.testing.assert_array_equal(automl.predict_proba(X_val), probabilities) + np.testing.assert_array_equal(automl.predict(X_val), predictions) @pytest.mark.parametrize("skip_transform", [True, False]) @@ -829,8 +833,11 @@ def test_rejected_refit_with_new_preprocessing_mode_preserves_installed_model(sk np.testing.assert_array_equal(automl.predict(X_val), predictions) -@pytest.mark.parametrize("skip_transform", [True, False]) -def test_failed_retrain_from_log_preserves_installed_model(tmp_path, skip_transform): +@pytest.mark.parametrize( + "skip_transform, retrain_task", + [(True, "classification"), (False, "classification"), (False, "regression"), (True, "regression")], +) +def test_failed_retrain_from_log_preserves_installed_model(tmp_path, skip_transform, retrain_task): rng = np.random.RandomState(131) X = rng.normal(size=(3000, 4)) y = np.arange(len(X)) % 2 @@ -861,16 +868,22 @@ def test_failed_retrain_from_log_preserves_installed_model(tmp_path, skip_transf probabilities = automl.predict_proba(X_val) assert probabilities.shape == (80, 3) + if retrain_task == "classification": + y_retrain, retrain_skip = 10 + 10 * (np.arange(3000) % 2), not skip_transform + else: + y_retrain, retrain_skip = np.arange(3000, dtype=float), skip_transform with pytest.raises(FileNotFoundError): automl.retrain_from_log( str(tmp_path / "missing.log"), X, - 10 + 10 * (np.arange(3000) % 2), - task="classification", - skip_transform=not skip_transform, + y_retrain, + task=retrain_task, + skip_transform=retrain_skip, ) assert automl.model is installed + assert automl._state.task.name == "multiclass" + assert automl._estimator_type == "classifier" assert automl._transformer is preprocessing[0] assert automl._label_transformer is preprocessing[1] np.testing.assert_array_equal(automl.classes_, [0, 1, 2]) From 525aef100cf3ae6761b0209b2fb08c6358ba645c Mon Sep 17 00:00:00 2001 From: Aryan Rajesh Ganjoo <51299383+AryanRG@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:31:26 +0530 Subject: [PATCH 12/14] Hold the installed model weakly during refits --- flaml/automl/automl.py | 17 +++++++++++++++-- test/automl/test_holdout_labels.py | 24 ++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/flaml/automl/automl.py b/flaml/automl/automl.py index 7c4e9181ce..04b45c27a9 100644 --- a/flaml/automl/automl.py +++ b/flaml/automl/automl.py @@ -11,6 +11,7 @@ import random import sys import time +import weakref from concurrent.futures import as_completed from functools import partial, wraps from typing import Callable, List, Optional, Union @@ -94,12 +95,23 @@ def size(learner_classes: dict, config: dict) -> float: return learner_class.size(config) +def _model_ref(model): + """Return a callable that yields ``model``, holding it weakly when possible.""" + if model is None: + return None + try: + return weakref.ref(model) + except TypeError: + return lambda: model + + def _keep_installed_preprocessing(fit): """Restore the installed model's task and preprocessing if a fit fails before replacing it.""" @wraps(fit) def wrapper(self, *args, **kwargs): - installed = getattr(self, "_trained_estimator", None) + # Hold the installed model weakly so search can still free it once it is discarded. + installed = _model_ref(getattr(self, "_trained_estimator", None)) names = ("_transformer", "_label_transformer", "_classes", "_estimator_type") preprocessing = [getattr(self, name, None) for name in names] state = getattr(self, "_state", None) @@ -107,7 +119,8 @@ def wrapper(self, *args, **kwargs): try: return fit(self, *args, **kwargs) except BaseException: - if installed is not None and getattr(self, "_trained_estimator", None) is installed: + model = installed() if installed is not None else None + if model is not None and getattr(self, "_trained_estimator", None) is model: for name, value in zip(names, preprocessing): setattr(self, name, value) if state is not None: diff --git a/test/automl/test_holdout_labels.py b/test/automl/test_holdout_labels.py index ebd5944e28..37a8f32157 100644 --- a/test/automl/test_holdout_labels.py +++ b/test/automl/test_holdout_labels.py @@ -1,4 +1,6 @@ +import gc import pickle +import weakref from types import SimpleNamespace import numpy as np @@ -890,6 +892,28 @@ def test_failed_retrain_from_log_preserves_installed_model(tmp_path, skip_transf np.testing.assert_array_equal(automl.predict_proba(X_val), probabilities) +def test_refit_releases_discarded_model_before_search(monkeypatch): + rng = np.random.RandomState(0) + X = rng.normal(size=(600, 4)) + y = np.arange(600) % 3 + settings = dict(task="classification", estimator_list=["lgbm"], n_jobs=1, verbose=0, max_iter=2, seed=1) + automl = AutoML() + automl.fit(X, y, **settings) + discarded = weakref.ref(automl.model) + alive_during_search = [] + search = AutoML._search_sequential + + def checked_search(self): + gc.collect() + alive_during_search.append(discarded() is not None) + return search(self) + + monkeypatch.setattr(AutoML, "_search_sequential", checked_search) + automl.fit(X, y, **settings) + + assert alive_during_search == [False] + + @pytest.mark.parametrize("estimator_class", [SparkNaiveBayesEstimator, SparkGBTEstimator]) @pytest.mark.parametrize("return_all", [False, True]) def test_spark_probability_facade_bypasses_missing_class_metadata(monkeypatch, estimator_class, return_all): From 11bc9b1185a3025c19ea57c4fdc64251c21e99bf Mon Sep 17 00:00:00 2001 From: Aryan Rajesh Ganjoo <51299383+AryanRG@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:42:25 +0530 Subject: [PATCH 13/14] Align HistGB probabilities for single-class samples --- flaml/automl/ml.py | 3 ++- test/automl/test_holdout_labels.py | 34 ++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/flaml/automl/ml.py b/flaml/automl/ml.py index 9053fd85ed..a135472c8b 100644 --- a/flaml/automl/ml.py +++ b/flaml/automl/ml.py @@ -8,6 +8,7 @@ from typing import Callable, Optional, Tuple, TypeVar, Union import numpy as np +from sklearn.ensemble import HistGradientBoostingClassifier from xgboost import XGBClassifier from flaml.automl.data import group_counts @@ -616,7 +617,7 @@ def _align_class_probabilities(predictions, estimator, labels): and probabilities.shape[1] == 2 and len(np.unique(labels)) > 1 and ( - isinstance(getattr(estimator, "model", estimator), XGBClassifier) + isinstance(getattr(estimator, "model", estimator), (XGBClassifier, HistGradientBoostingClassifier)) or (LGBMClassifier is not None and isinstance(getattr(estimator, "model", estimator), LGBMClassifier)) ) ): diff --git a/test/automl/test_holdout_labels.py b/test/automl/test_holdout_labels.py index 37a8f32157..36ec7ebd60 100644 --- a/test/automl/test_holdout_labels.py +++ b/test/automl/test_holdout_labels.py @@ -575,6 +575,40 @@ def recording(config, estimator, X_train, y_train, X_val, y_val, *args, **kwargs np.testing.assert_array_equal(automl.model.predict_proba(automl.preprocess(X_val)), raw) +def test_histgb_single_class_sample_preserves_probability_labels(): + rng = np.random.RandomState(81) + y = np.full(3000, 20) + y[[1500, 2500]] = 10 + X = rng.randn(len(y), 4) + X_val = rng.randn(300, 4) + y_val = np.resize([10, 20], len(X_val)) + automl = AutoML() + automl.fit( + X, + y, + X_val=X_val, + y_val=y_val, + task="classification", + metric="log_loss", + estimator_list=["histgb"], + max_iter=2, + seed=1, + min_sample_size=50, + sample=True, + starting_points={}, + auto_augment=False, + n_jobs=1, + verbose=0, + retrain_full=False, + skip_transform=True, + ) + np.testing.assert_array_equal(automl.model.classes_, [20]) + np.testing.assert_array_equal(automl.classes_, [10, 20]) + probabilities = automl.predict_proba(X_val) + np.testing.assert_array_equal(automl.classes_[probabilities.argmax(axis=1)], automl.predict(X_val)) + assert automl.best_loss == pytest.approx(log_loss(y_val, probabilities, labels=automl.classes_)) + + @pytest.mark.parametrize("input_mode", ["skip", "sparse"]) @pytest.mark.parametrize("missing_class", [10, 20, 30]) def test_native_sampled_lightgbm_probability_columns(input_mode, missing_class): From e4f9a0a1a849253489712b5d78b092acb7e4134e Mon Sep 17 00:00:00 2001 From: Aryan Rajesh Ganjoo <51299383+AryanRG@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:24:17 +0530 Subject: [PATCH 14/14] Strengthen HistGB holdout probability regression --- flaml/automl/automl.py | 2 +- test/automl/test_holdout_labels.py | 9 +++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/flaml/automl/automl.py b/flaml/automl/automl.py index 04b45c27a9..6aed628bb8 100644 --- a/flaml/automl/automl.py +++ b/flaml/automl/automl.py @@ -957,7 +957,7 @@ def predict_proba(self, X, **pred_kwargs): (i, j) is the probability for instance i to be in class `classes_[j]`. For tabular classification, classes absent from a retained sampled model receive zero probability, including with sparse inputs or disabled - preprocessing. A single-class LightGBM or XGBoost sample is + preprocessing. A single-class LightGBM, XGBoost, or HistGB sample is normalized over its observed class; non-finite backend rows remain non-finite. These aligned probabilities can therefore differ from the raw output of `automl.model.predict_proba(automl.preprocess(X))`. diff --git a/test/automl/test_holdout_labels.py b/test/automl/test_holdout_labels.py index 36ec7ebd60..75f838c76b 100644 --- a/test/automl/test_holdout_labels.py +++ b/test/automl/test_holdout_labels.py @@ -581,7 +581,8 @@ def test_histgb_single_class_sample_preserves_probability_labels(): y[[1500, 2500]] = 10 X = rng.randn(len(y), 4) X_val = rng.randn(300, 4) - y_val = np.resize([10, 20], len(X_val)) + # Unequal class counts make reversed scoring columns change the loss. + y_val = np.resize([10, 20, 20], len(X_val)) automl = AutoML() automl.fit( X, @@ -604,9 +605,9 @@ def test_histgb_single_class_sample_preserves_probability_labels(): ) np.testing.assert_array_equal(automl.model.classes_, [20]) np.testing.assert_array_equal(automl.classes_, [10, 20]) - probabilities = automl.predict_proba(X_val) - np.testing.assert_array_equal(automl.classes_[probabilities.argmax(axis=1)], automl.predict(X_val)) - assert automl.best_loss == pytest.approx(log_loss(y_val, probabilities, labels=automl.classes_)) + expected = np.broadcast_to([0.0, 1.0], (len(X_val), 2)) + np.testing.assert_array_equal(automl.predict_proba(X_val), expected) + assert automl.best_loss == pytest.approx(log_loss(y_val, expected, labels=automl.classes_)) @pytest.mark.parametrize("input_mode", ["skip", "sparse"])