Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions flaml/automl/task/generic_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,12 @@ def validate_data(
else:
state.groups_val = groups_val
state.groups = groups
# positional indexing of the group labels (holdout and CV splits) needs an ndarray:
# a list has no iloc and a Series with a non-default index would be indexed by label
if isinstance(state.groups, (list, tuple, pd.Series)):
state.groups = np.asarray(state.groups)
if isinstance(state.groups_val, (list, tuple, pd.Series)):
state.groups_val = np.asarray(state.groups_val)

automl.data_size_full = len(automl._y_train_all)

Expand Down
259 changes: 259 additions & 0 deletions test/automl/test_split.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,265 @@ def spy_fit(self, X, y, sample_weight=None, **kwargs):
assert automl._state.weight_val is not None


@pytest.mark.parametrize("eval_method", ["holdout", "cv"])
@pytest.mark.parametrize("kind", ["list", "tuple", "series_offset_index", "group_kfold_list"])
def test_group_split_with_non_array_groups(kind, eval_method):
"""groups may be any array-like: a list, a tuple or a pd.Series whose index is not 0..n-1."""
from unittest.mock import patch

from sklearn.ensemble import RandomForestClassifier

if kind == "group_kfold_list" and eval_method != "cv":
pytest.skip("a splitter object requires eval_method='cv'")
n = 200
rng = np.random.default_rng(7)
X = pd.DataFrame({"id": np.arange(n, dtype=float), "feat": rng.normal(size=n)})
group_labels = np.repeat(np.arange(20), 10)
y = pd.Series((group_labels % 2).astype(int))
groups = {
"list": group_labels.tolist(),
"tuple": tuple(group_labels.tolist()),
"series_offset_index": pd.Series(group_labels, index=np.arange(n) + 500),
"group_kfold_list": group_labels.tolist(),
}[kind]
split_type = GroupKFold(3) if kind == "group_kfold_list" else "group"

captured = []
original_fit = RandomForestClassifier.fit

def spy_fit(self, X, y, **kwargs):
captured.append(np.asarray(X)[:, 0].copy())
return original_fit(self, X, y, **kwargs)

automl = AutoML()
with patch.object(RandomForestClassifier, "fit", spy_fit):
automl.fit(
X_train=X,
y_train=y,
groups=groups,
split_type=split_type,
eval_method=eval_method,
n_splits=3,
task="classification",
time_budget=-1,
max_iter=2,
estimator_list=["rf"],
verbose=0,
)
assert automl.model is not None
assert captured
all_counts = [np.bincount((ids // 10).astype(int), minlength=20) for ids in captured]
for counts in all_counts:
# every fit sees whole groups only: a group is never split between train and validation
assert set(counts) <= {0, 10}
# at least one fit actually holds some groups out
assert any(0 in counts for counts in all_counts)


def _spy_val_loss_calls():
"""record the rows, the training group labels and the validation group labels of every evaluated fold"""
from flaml.automl import ml

calls = []
original = ml.get_val_loss # the CV path calls the same function through generic_task

def spy(config, estimator, X_train, y_train, X_val, y_val, weight_val, groups_val, *args, **kwargs):
fit_kwargs = kwargs.get("fit_kwargs") or (args[-1] if args and isinstance(args[-1], dict) else {})
calls.append(
{
"train_ids": np.asarray(X_train)[:, 0].astype(int),
"val_ids": np.asarray(X_val)[:, 0].astype(int),
"groups": fit_kwargs.get("groups"),
"groups_val": groups_val,
}
)
return original(config, estimator, X_train, y_train, X_val, y_val, weight_val, groups_val, *args, **kwargs)

return calls, spy


@pytest.mark.parametrize("eval_method", ["holdout", "cv"])
@pytest.mark.parametrize("kind", ["list", "series_offset_index", "series_permuted_index"])
def test_group_labels_follow_rows_in_every_fold(kind, eval_method):
"""the group labels handed to each fold are the labels of the rows in that fold"""
from unittest.mock import patch

n = 200
rng = np.random.default_rng(3)
X = pd.DataFrame({"id": np.arange(n, dtype=float), "feat": rng.normal(size=n)})
labels = np.repeat(np.arange(20), 10)
y = pd.Series((labels % 2).astype(int))
groups = {
"list": labels.tolist(),
"series_offset_index": pd.Series(labels, index=np.arange(n) + 500),
"series_permuted_index": pd.Series(labels, index=rng.permutation(n)),
}[kind]
calls, spy = _spy_val_loss_calls()
with patch("flaml.automl.ml.get_val_loss", spy), patch("flaml.automl.task.generic_task.get_val_loss", spy):
AutoML().fit(
X_train=X,
y_train=y,
groups=groups,
split_type="group",
eval_method=eval_method,
n_splits=3,
task="classification",
time_budget=-1,
max_iter=2,
estimator_list=["rf"],
verbose=0,
)
assert calls
held_out = False
for call in calls:
assert call["groups_val"] is not None
np.testing.assert_array_equal(np.asarray(call["groups_val"]), labels[call["val_ids"]])
assert call["groups"] is not None
np.testing.assert_array_equal(np.asarray(call["groups"]), labels[call["train_ids"]])
train_groups, val_groups = set(labels[call["train_ids"]]), set(labels[call["val_ids"]])
assert not train_groups & val_groups
held_out |= bool(val_groups)
assert held_out


@pytest.mark.parametrize("kind", ["list", "series_offset_index", "series_permuted_index"])
def test_group_cv_validation_folds_partition_the_rows(kind):
"""three-fold group CV: the validation sets are disjoint, cover every row and hold whole groups"""
from unittest.mock import patch

n = 200
rng = np.random.default_rng(11)
X = pd.DataFrame({"id": np.arange(n, dtype=float), "feat": rng.normal(size=n)})
labels = np.repeat(np.arange(20), 10)
y = pd.Series((labels % 2).astype(int))
groups = {
"list": labels.tolist(),
"series_offset_index": pd.Series(labels, index=np.arange(n) + 500),
"series_permuted_index": pd.Series(labels, index=rng.permutation(n)),
}[kind]
calls, spy = _spy_val_loss_calls()
with patch("flaml.automl.ml.get_val_loss", spy), patch("flaml.automl.task.generic_task.get_val_loss", spy):
AutoML().fit(
X_train=X,
y_train=y,
groups=groups,
split_type="group",
eval_method="cv",
n_splits=3,
task="classification",
time_budget=-1,
max_iter=2,
estimator_list=["rf"],
verbose=0,
)
# every evaluated configuration is scored on exactly three folds
assert calls and len(calls) % 3 == 0
for start in range(0, len(calls), 3):
_check_cv_folds(calls[start : start + 3], labels, n)


def _check_cv_folds(calls, labels, n):
val_sets = [set(call["val_ids"].tolist()) for call in calls]
assert all(val_sets)
assert sum(len(v) for v in val_sets) == n # pairwise disjoint (sizes add up to n) ...
assert set().union(*val_sets) == set(range(n)) # ... and together they cover every row
for call, val in zip(calls, val_sets):
train = set(call["train_ids"].tolist())
assert not train & val
assert train | val == set(range(n))
# whole groups only: the validation labels match the rows and no group is on both sides
np.testing.assert_array_equal(np.asarray(call["groups_val"]), labels[call["val_ids"]])
assert not set(labels[call["train_ids"]]) & set(labels[call["val_ids"]])


@pytest.mark.parametrize("kind", ["list", "tuple", "series_offset_index"])
def test_group_labels_with_caller_supplied_validation_data(kind):
"""X_val / y_val with non-array groups and groups_val: labels stay aligned with their rows"""
from unittest.mock import patch

n_train = 160
rng = np.random.default_rng(5)
X_all = pd.DataFrame({"id": np.arange(200, dtype=float), "feat": rng.normal(size=200)})
labels_all = np.repeat(np.arange(20), 10)
y_all = pd.Series((labels_all % 2).astype(int))
X_train, X_val = X_all.iloc[:n_train], X_all.iloc[n_train:].reset_index(drop=True)
y_train, y_val = y_all.iloc[:n_train], y_all.iloc[n_train:].reset_index(drop=True)
labels_train, labels_val = labels_all[:n_train], labels_all[n_train:]
wrap = {
"list": lambda a: a.tolist(),
"tuple": lambda a: tuple(a.tolist()),
"series_offset_index": lambda a: pd.Series(a, index=np.arange(len(a)) + 500),
}[kind]
calls, spy = _spy_val_loss_calls()
with patch("flaml.automl.ml.get_val_loss", spy), patch("flaml.automl.task.generic_task.get_val_loss", spy):
automl = AutoML()
automl.fit(
X_train=X_train,
y_train=y_train,
X_val=X_val,
y_val=y_val,
groups=wrap(labels_train),
groups_val=wrap(labels_val),
split_type="group",
eval_method="holdout",
task="classification",
time_budget=-1,
max_iter=2,
estimator_list=["rf"],
verbose=0,
)
assert automl.model is not None
assert calls
for call in calls:
np.testing.assert_array_equal(call["val_ids"], X_val["id"].to_numpy().astype(int))
# the captured labels are indexed by position directly, the way the estimators use them
assert [call["groups_val"][i] for i in range(len(labels_val))] == labels_val.tolist()
assert call["groups"] is not None
np.testing.assert_array_equal(np.asarray(call["groups"]), labels_train[call["train_ids"]])


def test_group_holdout_with_permuted_index_series_keeps_group_alignment():
"""A Series whose index is a permutation of 0..n-1 does not raise, but was indexed by label."""
from unittest.mock import patch

from flaml.automl.task.generic_task import GenericTask

snapshot = {}
original = GenericTask.prepare_data

def spy(self, state, *args, **kwargs):
out = original(self, state, *args, **kwargs)
snapshot.update(
train_ids=np.asarray(state.X_train)[:, 0].astype(int),
val_ids=np.asarray(state.X_val)[:, 0].astype(int),
groups=np.asarray(state.groups),
groups_val=np.asarray(state.groups_val),
)
return out

n = 200
rng = np.random.default_rng(0)
X = pd.DataFrame({"id": np.arange(n, dtype=float), "feat": rng.normal(size=n)})
labels = np.repeat(np.arange(20), 10)
y = pd.Series((labels % 2).astype(int))
groups = pd.Series(labels, index=rng.permutation(n)) # values in row order, shuffled index labels
with patch.object(GenericTask, "prepare_data", spy):
AutoML().fit(
X_train=X,
y_train=y,
groups=groups,
split_type="group",
eval_method="holdout",
task="classification",
time_budget=-1,
max_iter=2,
estimator_list=["rf"],
verbose=0,
)
np.testing.assert_array_equal(snapshot["groups"], labels[snapshot["train_ids"]])
np.testing.assert_array_equal(snapshot["groups_val"], labels[snapshot["val_ids"]])


@pytest.mark.skipif(
sys.platform == "win32" and platform.machine() == "ARM64", reason="catboost is not available on win-arm64 machine"
)
Expand Down
Loading