bind_groups
- class bind_groups(cv, groups, *, allow_overlap=False)[source]
Bind group labels to a cross-validation splitter, so dependent samples stay in one fold.
Protein datasets are full of dependent samples: several windows cut from one protein, or near-identical homologues across a family. A plain split scatters them over train and test, so a model is scored partly on what it already saw and the reported performance is inflated. A scikit-learn group splitter prevents that, but it needs a
groupsarray at split time, and the evaluation entry points of this package callcross_val_*without one. Binding the labels to the splitter closes that gap: the returned object carries them and is accepted anywhere a splitter is, soevalis unchanged [Roberts17].The group vocabulary is whatever is passed: an accession keeps each protein whole, a family or an externally computed homology cluster keeps each family whole. The package performs the split and reports its properties; it runs no homology search or clustering itself.
Added in version 1.2.0.
- Parameters:
cv (splitter) – A scikit-learn splitter instance whose folds are to respect the groups, e.g.
GroupKFold(n_splits=5),StratifiedGroupKFold(n_splits=5)(keeps the class balance too) orLeaveOneGroupOut()(leave-one-protein-out). Its own parameters, includingrandom_state, are untouched, so reproducibility is the splitter’s.groups (array-like, shape (n_samples,)) – Group label per sample, aligned with the rows of
X: a protein accession, a family name, or a cluster id. Any hashable labels work; the number of distinct values is the number of groups.allow_overlap (bool, default=False) – Whether a group may appear in both train and test of a fold.
Falseverifies every fold and raises aValueErrornaming the shared groups, which turns a splitter that ignores groups (e.g.KFold) into an error instead of a silent leak.
- Returns:
cv_bound – Splitter with the group labels bound, to pass as
cvtoAAPred.eval,ModelEvaluator.runor any scikit-learn routine. Once its folds are consumed, the attributedf_folds_holds one row per fold with the columnsfold,n_train,n_test,n_groups_train,n_groups_test,pos_rate_trainandpos_rate_test(the two rates areNaNwhen labels were not passed).- Return type:
splitter
Notes
Group splitters trade exactness for independence:
GroupKFoldcannot balance the folds as evenly asKFold, so fold sizes differ. Inspectdf_folds_rather than assuming equal folds.A splitter whose test folds do not partition the samples (e.g.
GroupShuffleSplit) works for scoring but not where every sample needs one out-of-fold prediction.Comparing a grouped score against an ungrouped one on the same data measures the leak; report the grouped score as the honest one.
See also
AAPredand itsevalmethod, which takes the returned object ascv.ModelEvaluatorfor repeated cross-validation with confidence intervals.SequenceFeature.get_split_kws(), which splits a sequence into parts, unrelated to the cross-validation splits meant here.
Examples
Bind group labels to a cross-validation splitter.
Protein datasets are full of dependent samples: several windows cut from one protein, or near-identical homologues across a family. A plain split scatters them over train and test, so the model is scored partly on what it already saw and the reported performance is inflated.
aa.bind_groupsbinds a group label per sample to any scikit-learn splitter, so the splitter can be passed straight toAAPred.eval— which callscross_val_*without agroupsargument — and every group stays whole within one fold.import numpy as np import pandas as pd from sklearn.model_selection import (GroupKFold, StratifiedGroupKFold, LeaveOneGroupOut, StratifiedKFold, KFold) import aaanalysis as aa aa.options["verbose"] = False # Twelve proteins, six near-identical windows each. The label is a property of the # PROTEIN, so a window carries no information its siblings do not already carry. rng = np.random.default_rng(0) n_prot, n_win = 12, 6 groups = np.repeat([f"P{i}" for i in range(n_prot)], n_win) labels = np.repeat(rng.integers(0, 2, n_prot), n_win) base = rng.random((n_prot, 8)) X = np.repeat(base, n_win, axis=0) + rng.normal(0, 0.01, (n_prot * n_win, 8)) df_seq = pd.DataFrame({"entry": groups, "label": labels}) aa.display_df(df_seq, n_rows=10, show_shape=True)
DataFrame shape: (72, 2)
entry label 1 P0 1 2 P0 1 3 P0 1 4 P0 1 5 P0 1 6 P0 1 7 P1 1 8 P1 1 9 P1 1 10 P1 1 ``cv`` and ``groups``: bind the labels to a splitter.
cvis a splitter instance;groupsholds one label per sample, aligned with the rows ofX. Any hashable labels work: an accession keeps each protein whole, a family name or an external homology cluster keeps each family whole.cv = aa.bind_groups(GroupKFold(n_splits=4), groups=groups) cv
bind_groups(GroupKFold(), n_groups=12)
The leak this prevents.
The same data, the same model, two splitters. A random split reports near-perfect accuracy because each test window has near-identical siblings in the training set; the protein-grouped split reports what the model can actually do on an unseen protein.
aap = aa.AAPred(verbose=False, random_state=42) df_random = aap.eval(X, labels=labels, metrics=["accuracy"], cv=StratifiedKFold(n_splits=4, shuffle=True, random_state=42)) df_grouped = aap.eval(X, labels=labels, metrics=["accuracy"], cv=aa.bind_groups(StratifiedGroupKFold(n_splits=4), groups=groups)) df_comp = pd.DataFrame({"split": ["random (leaky)", "protein-grouped"], "accuracy": [df_random["score"].iloc[0], df_grouped["score"].iloc[0]]}) aa.display_df(df_comp, n_rows=10, show_shape=True)
DataFrame shape: (2, 2)
split accuracy 1 random (leaky) 1.000000 2 protein-grouped 0.666667 evalis unchanged: the splitter is the only new surface. Report the grouped score as the honest one.Inspecting the folds with ``df_folds_``.
Once the folds are consumed, the bound splitter records one row per fold, so the group sizes and the class balance of each fold can be checked rather than assumed. Group splitters cannot balance folds as evenly as
KFold, which is a property to inspect, not a defect.cv = aa.bind_groups(StratifiedGroupKFold(n_splits=4), groups=groups) _ = list(cv.split(X, labels)) aa.display_df(cv.df_folds_, n_rows=10, show_shape=True)
DataFrame shape: (4, 7)
fold n_train n_test n_groups_train n_groups_test pos_rate_train pos_rate_test 1 0 54 18 9 3 0.555556 0.333333 2 1 54 18 9 3 0.555556 0.333333 3 2 54 18 9 3 0.444444 0.666667 4 3 54 18 9 3 0.444444 0.666667 Other splitters: leave-one-protein-out and leave-one-cluster-out.
The vocabulary lives in what is passed as
groups, so one mechanism covers every strategy.LeaveOneGroupOutover accessions is leave-one-protein-out; over cluster ids it is leave-one-cluster-out.cv_lopo = aa.bind_groups(LeaveOneGroupOut(), groups=groups) print("leave-one-protein-out folds:", cv_lopo.get_n_splits(X, labels)) # Externally computed homology clusters (three proteins per family here) clusters = np.repeat([f"family{i // 3}" for i in range(n_prot)], n_win) cv_locluster = aa.bind_groups(LeaveOneGroupOut(), groups=clusters) print("leave-one-cluster-out folds:", cv_locluster.get_n_splits(X, labels))
leave-one-protein-out folds: 12 leave-one-cluster-out folds: 4
``allow_overlap``: the guard against a silent leak.
By default every fold is verified and a splitter that ignores groups raises a
ValueErrornaming the shared groups. Setallow_overlap=Trueto permit overlap deliberately, e.g. to reproduce an ungrouped baseline.groups_interleaved = np.tile([f"P{i}" for i in range(n_prot)], n_win) try: list(aa.bind_groups(KFold(n_splits=4), groups=groups_interleaved).split(X, labels)) except ValueError as e: print("ValueError:", e) cv_overlap = aa.bind_groups(KFold(n_splits=4), groups=groups_interleaved, allow_overlap=True) print("\nallow_overlap=True folds:", len(list(cv_overlap.split(X, labels))))
ValueError: 'cv' put 12 group(s) in both train and test of fold 0 (e.g. 'P0'), which leaks between folds. Use a group-aware splitter (e.g. 'GroupKFold', 'StratifiedGroupKFold', 'LeaveOneGroupOut') or set 'allow_overlap=True' to permit it allow_overlap=True folds: 4
/Users/stephanbreimann/Programming/1Packages/aaanalysis/.venv/lib/python3.13/site-packages/sklearn/model_selection/_split.py:86: UserWarning: The groups parameter is ignored by KFold warnings.warn( /Users/stephanbreimann/Programming/1Packages/aaanalysis/.venv/lib/python3.13/site-packages/sklearn/model_selection/_split.py:86: UserWarning: The groups parameter is ignored by KFold warnings.warn(
Infeasible fold counts.
Asking for more folds than there are groups cannot be satisfied without splitting a group, so it is rejected at construction with both counts in the message.
try: aa.bind_groups(GroupKFold(n_splits=20), groups=groups) except ValueError as e: print("ValueError:", e)
ValueError: 'n_splits' (20) of 'cv' (GroupKFold) should be <= the number of distinct groups (n groups=12); a fold cannot be filled without splitting a group