diff --git a/flaml/automl/automl.py b/flaml/automl/automl.py index b05f98b24d..6aed628bb8 100644 --- a/flaml/automl/automl.py +++ b/flaml/automl/automl.py @@ -11,8 +11,9 @@ import random import sys import time +import weakref 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 @@ -20,12 +21,14 @@ from flaml import tune from flaml.automl.logger import logger, logger_formatter from flaml.automl.ml import ( + _align_class_probabilities, huggingface_metric_to_mode, sklearn_metric_name_set, spark_metric_name_dict, 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 @@ -92,6 +95,41 @@ 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): + # 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) + task = getattr(state, "task", None) + try: + return fit(self, *args, **kwargs) + except BaseException: + 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: + state.task = task + raise + + return wrapper + + # metrics that sklearn only computes for binary targets BINARY_ONLY_METRICS = ("roc_auc", "roc_auc_weighted", "ap", "f1") @@ -803,10 +841,17 @@ def label_transformer(self): @property def classes_(self): - """A numpy array of shape (n_classes,) for class labels.""" + """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_ + classes = getattr(self, "_classes", None) + if classes is not None: + return classes attr = getattr(self, "_trained_estimator", None) if attr: return attr.classes_ @@ -907,8 +952,18 @@ 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 - (i, j) is the probability for instance i to be in class j. + 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 + 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))`. + 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: @@ -916,6 +971,18 @@ 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 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_ + proba = _align_class_probabilities(proba, estimator, labels) return proba def preprocess( @@ -1013,6 +1080,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, @@ -1227,6 +1295,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 @@ -1276,6 +1345,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 @@ -1849,6 +1919,9 @@ 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.native_classes = None self._state.task.prepare_data( self._state, self._X_train_all, @@ -1862,8 +1935,27 @@ 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" 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. + labels = labels.to_numpy() if isinstance(labels, psSeries) else labels + if eval_method == "holdout": + self._state.holdout_labels = labels + if native_class_axis: + self._state.native_classes = labels self.data_size_full = self._state.data_size_full + @_keep_installed_preprocessing def fit( self, X_train=None, @@ -3286,6 +3378,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/flaml/automl/ml.py b/flaml/automl/ml.py index a21e35b7e3..a135472c8b 100644 --- a/flaml/automl/ml.py +++ b/flaml/automl/ml.py @@ -4,14 +4,19 @@ # * 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 +from sklearn.ensemble import HistGradientBoostingClassifier +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 +from flaml.automl.task.factory import task_factory from flaml.automl.task.task import Task from flaml.automl.time_series import TimeSeriesDataset @@ -350,7 +355,11 @@ def compute_estimator( log_training_metric: Optional[bool] = False, 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 = {} @@ -376,6 +385,19 @@ 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 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 + 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, @@ -387,7 +409,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, @@ -580,6 +602,49 @@ def default_cv_score_agg_func(val_loss_folds, log_metrics_folds): return metric_to_minimize, metrics_to_log +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) + probabilities = np.asarray(predictions) + if classes is None or probabilities.ndim != 2: + return predictions + # 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)) > 1 + and ( + isinstance(getattr(estimator, "model", estimator), (XGBClassifier, HistGradientBoostingClassifier)) + or (LGBMClassifier is not None and isinstance(getattr(estimator, "model", estimator), LGBMClassifier)) + ) + ): + # 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 + labels = np.asarray(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 _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, @@ -598,6 +663,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? @@ -637,6 +704,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, @@ -650,7 +719,7 @@ def _eval_estimator( X_val, y_val, estimator, - labels, + copy(labels), X_train, y_train, weight_val, diff --git a/flaml/automl/state.py b/flaml/automl/state.py index e5469e1ebe..9c35a359f9 100644 --- a/flaml/automl/state.py +++ b/flaml/automl/state.py @@ -323,6 +323,8 @@ def _compute_with_config_base( state.log_training_metric, 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 new file mode 100644 index 0000000000..75f838c76b --- /dev/null +++ b/test/automl/test_holdout_labels.py @@ -0,0 +1,1250 @@ +import gc +import pickle +import weakref +from types import SimpleNamespace + +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 + +from flaml import AutoML +from flaml.automl import ml +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 + +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 + + +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] + 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("input_mode", ["transform", "skip", "sparse"]) +@pytest.mark.parametrize("retrain_full", [False, True]) +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 + + 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, + y, + eval_method="holdout", + metric="log_loss", + sample=False, + skip_transform=input_mode == "skip", + **{**SETTINGS, "retrain_full": retrain_full}, + ) + + 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_, np.unique(y)) + + +@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 + 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_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 + 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 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") + 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) + + +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) + 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("learner", ["lgbm", "xgboost", "xgb_limitdepth"]) +@pytest.mark.parametrize("log_training_metric", [False, True]) +@pytest.mark.parametrize("num_classes", [2, 3]) +@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 + + 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) + 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, + labels[y], + X_val=X_val, + y_val=labels[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 + 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) + 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"]) +@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(X_val.shape[0]) % 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, + skip_transform=input_mode == "skip", + ) + np.testing.assert_array_equal(automl.model.classes_, [0]) + 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 == (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), + ("lgbm", ["a", "b", "c"], "b"), + ("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) + + +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) + # 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, + 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]) + 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"]) +@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"]) +@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): + 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( + 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("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", "transform"]) +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) + 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]) +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, 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 + 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) + + 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, + 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]) + 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): + # 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): + 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(X_val.shape[0]) % 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, + skip_transform=input_mode == "skip", + ) + 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 == (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) + + +@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( + "sole_class, labels", + [(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): + 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) + + +@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])) + 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", + [ + ([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(labels is None for labels in seen) + np.testing.assert_array_equal(automl._state.holdout_labels, np.unique(current_y)) + assert calls == []