audit_leakage
- class audit_leakage(df_seq=None, *, labels=None, groups=None, splits=None, X=None, names=None, raise_on=None)[source]
Audit an evaluation setup for leakage risks and report them as a table of findings.
Leakage inflates a score without ever raising an error: a duplicated sequence on both sides of a split, two windows of one protein pulled apart, a feature quietly derived from the label. On the small, windowed datasets typical of sequence-based prediction these are easy to introduce and hard to see, and the only symptom is an implausibly good number. This function runs a set of cheap heuristics over whatever parts of the setup are supplied and lists what looks wrong, before a score is trusted [Kaufman12].
It works in two stages, each optional. Without
splitsonly the dataset itself is inspected, which is the check to run before choosing a split. Withsplitsthe folds are inspected too, comparing the training against the test part within each fold.Added in version 1.2.0.
- Parameters:
df_seq (pd.DataFrame, shape (n_samples, n_features), optional) – DataFrame containing an
entrycolumn with protein identifiers, one row per sample. An identifier repeats when several windows come from one protein, which is what the per-protein check looks for.'sequence', or'window'when present, is compared for duplicates; for windowed output the window is the sample, so it takes precedence over the parent'sequence'.labels (array-like, shape (n_samples,), optional) – Class labels per sample. Used for the class-balance and target-derived checks. Taken from
df_seq['label']when that column exists andlabelsis not given. Unlike elsewhere in this package, a single class is accepted, since it is itself reported.groups (array-like, shape (n_samples,), optional) – Group label per sample, as passed to
bind_groups(): a protein accession, a family name, or an externally computed homology cluster. A group in both parts of a fold is a leak.splits (iterable of (train_idx, test_idx), optional) – The folds to inspect, as integer row positions, e.g.
list(cv.split(X, labels))or the output of a splitter returned bybind_groups(). Without it only the dataset-level checks run.X (array-like, shape (n_samples, n_features), optional) – Feature matrix to inspect for columns that track the label too closely. Requires
labels.names (list of str, optional) – Feature name per column of
X, e.g.df_feat['feature'].to_list(), so a finding names the feature instead of its column position.raise_on (str, optional) – Severity at or above which a finding raises a
ValueErrorinstead of being reported: one of'low','medium'or'high'. The default reports only and never raises, so an audit can be added to a workflow without changing its control flow.
- Returns:
df_audit – Findings, one row per issue, worst first, with the columns
'check'(which heuristic fired),'severity'('low','medium'or'high'),'detail'(a sentence describing the finding and why it matters) and'ids'(the affected identifiers, at most 10 of them; the true count is in'detail'). A clean setup gives an empty frame with those columns.df_audit.attrs['status']carries the worst severity present, or'ok'when there is no finding.- Return type:
pd.DataFrame
- Raises:
ValueError – If the given inputs do not describe the same samples, if
splitsholds anything other than pairs of integer row positions within range, or ifraise_onis set and a finding reaches that severity.
Notes
The audit is heuristic, and a clean report is not a proof that no leakage exists. It inspects only the data and the folds it is given. It cannot see how a feature was built, whether a scaler was fitted before the split, or that two sequences are near-identical rather than byte-identical. Treat
status='ok'as “nothing obvious”, not as a guarantee.The severities are labels for a human reader, not a machine taxonomy: whether a finding must block a workflow is a policy decision this package deliberately leaves to the caller.
Thresholds are fixed so a report means the same thing everywhere: a feature correlates with the label at \(|r| \ge 0.95\), the largest test fold holds twice the rows of the smallest, or a fold’s class share departs from the whole dataset by more than 0.2.
Row positions, not index labels, are expected in
splits, matching scikit-learn. Adf_seqwith a non-default index is therefore audited by position.
See also
bind_groups()to prevent the group leak this reports, by keeping every group within one fold.AAPredandModelEvaluator, whosecvargument takes the splitter whose folds are audited here.
Examples
Audit an evaluation setup for leakage risks.
Leakage inflates a score without ever raising an error: a duplicated sequence on both sides of a split, two windows of one protein pulled apart, a feature quietly derived from the label. The only symptom is an implausibly good number.
aa.audit_leakageruns a set of cheap heuristics over whatever parts of a setup are given and returns a plain table of findings, worst first, with the overall verdict indf_audit.attrs["status"].import numpy as np import pandas as pd from sklearn.model_selection import KFold, GroupKFold, StratifiedKFold import aaanalysis as aa aa.options["verbose"] = False # Twelve proteins, four windows each. The label is a property of the PROTEIN, so the # windows of one protein are near-duplicates of each other. rng = np.random.default_rng(0) AA = list("ACDEFGHIKLMNPQRSTVWY") n_prot, n_win = 12, 4 rows = [] for i in range(n_prot): parent = "".join(rng.choice(AA, 60)) for w in range(n_win): rows.append({"entry": f"P{i}", "entry_win": f"P{i}_w{w}", "sequence": parent, "window": parent[w:w + 12], "label": i % 2}) df_seq = pd.DataFrame(rows) aa.display_df(df_seq, n_rows=10, show_shape=True)
DataFrame shape: (48, 5)
entry entry_win sequence window label 1 P0 P0_w0 VPMGHACAETPWMPY...QMPGPSILYTYIQYQ VPMGHACAETPW 0 2 P0 P0_w1 VPMGHACAETPWMPY...QMPGPSILYTYIQYQ PMGHACAETPWM 0 3 P0 P0_w2 VPMGHACAETPWMPY...QMPGPSILYTYIQYQ MGHACAETPWMP 0 4 P0 P0_w3 VPMGHACAETPWMPY...QMPGPSILYTYIQYQ GHACAETPWMPY 0 5 P1 P1_w0 TQRIVDNRTMIHKLR...VCCQHNEVLVSRFSC TQRIVDNRTMIH 1 6 P1 P1_w1 TQRIVDNRTMIHKLR...VCCQHNEVLVSRFSC QRIVDNRTMIHK 1 7 P1 P1_w2 TQRIVDNRTMIHKLR...VCCQHNEVLVSRFSC RIVDNRTMIHKL 1 8 P1 P1_w3 TQRIVDNRTMIHKLR...VCCQHNEVLVSRFSC IVDNRTMIHKLR 1 9 P2 P2_w0 NKYEWCPNVGWQVES...MFSCKGRRRWWEDDR NKYEWCPNVGWQ 0 10 P2 P2_w1 NKYEWCPNVGWQVES...MFSCKGRRRWWEDDR KYEWCPNVGWQV 0 ``df_seq``: the dataset-level audit, before any split.
With only
df_seqthe audit inspects the data itself. This is the check to run before choosing a split. Here nothing is wrong yet, so the table is empty and the status isok.df_audit = aa.audit_leakage(df_seq) print("status:", df_audit.attrs["status"]) aa.display_df(df_audit, n_rows=10, show_shape=True)
status: ok DataFrame shape: (0, 4)
check severity detail ids Note that the windows share a parent
sequencebut eachwindowis distinct. The audit compareswindowwhen it is present, so the repeated parent is not mistaken for a pile of duplicate samples. Duplicating an actual window does get flagged:df_dup = df_seq.copy() df_dup.loc[5, "window"] = df_dup.loc[0, "window"] # P1_w1 is now a copy of P0_w0 df_audit = aa.audit_leakage(df_dup) print("status:", df_audit.attrs["status"]) aa.display_df(df_audit, n_rows=10, show_shape=True)
status: medium DataFrame shape: (1, 4)
check severity detail ids 1 duplicate_sequences medium 2 rows share on...ready memorized ['P0_w0', 'P1_w1'] ``splits`` and ``labels``: the fold-level audit, after the split is built.
splitstakes the folds as integer row positions, exactly what a scikit-learn splitter yields, socv.split(...)can be passed straight in.labelsadds the class-balance check; it defaults todf_seq['label']when that column exists.A plain
KFoldscatters the windows of each protein across the folds, which is the classic windowed-data leak.labels = df_seq["label"].to_numpy() splits_leaky = list(KFold(n_splits=4, shuffle=True, random_state=0).split(df_seq)) df_audit = aa.audit_leakage(df_seq, labels=labels, splits=splits_leaky) print("status:", df_audit.attrs["status"]) aa.display_df(df_audit, n_rows=10, show_shape=True)
status: high DataFrame shape: (1, 4)
check severity detail ids 1 same_protein_across_folds high 12 protein(s) h...cross the split ['P0', 'P1', 'P10', 'P11', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7'] # The full sentence of the first finding, which is where the reasoning lives for _, row in df_audit.iterrows(): print(f"[{row['severity']}] {row['check']}\n {row['detail']}\n ids: {row['ids']}\n")
[high] same_protein_across_folds 12 protein(s) have windows in both the training and the test part of fold(s) 0, 1, 2, 3, so neighbouring windows leak across the split ids: ['P0', 'P1', 'P10', 'P11', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7']
``groups``: the same audit in the group vocabulary.
groupsis one label per sample, exactly as passed toaa.bind_groups: an accession, a family, or an externally computed homology cluster. Binding those groups to a group-aware splitter is the fix, and the audit confirms the leak is gone.groups = df_seq["entry"].to_numpy() cv = aa.bind_groups(GroupKFold(n_splits=4), groups=groups) splits_clean = list(cv.split(df_seq)) df_audit = aa.audit_leakage(df_seq, labels=labels, groups=groups, splits=splits_clean) print("status:", df_audit.attrs["status"]) aa.display_df(df_audit, n_rows=10, show_shape=True)
status: high DataFrame shape: (1, 4)
check severity detail ids 1 class_balance_anomaly high the test part o...ially satisfied ['0', '1', '2', '3'] The protein and group leaks are gone. What remains is a true property of this setup: grouping by protein while the label is a property of the protein leaves some folds single-class. That is worth knowing before trusting a score, which is exactly the point.
``X`` and ``names``: features that track the label too closely.
Xis the feature matrix andnamesgives one name per column, e.g.df_feat['feature'].to_list(), so a finding names the feature instead of its column position. A feature correlating with the label at|r| >= 0.95is what a target-derived column looks like.X = rng.random((len(df_seq), 4)) X[:, 2] = labels + rng.random(len(df_seq)) * 0.01 # quietly derived from the target names = ["hydrophobicity", "charge", "leaky_feature", "helix_propensity"] df_audit = aa.audit_leakage(df_seq, labels=labels, X=X, names=names) print("status:", df_audit.attrs["status"]) aa.display_df(df_audit, n_rows=10, show_shape=True)
status: high DataFrame shape: (1, 4)
check severity detail ids 1 target_derived_feature high 1 feature(s) co...thout the label ['leaky_feature'] ``raise_on``: turn a report into a hard failure.
By default the audit only reports, so it can be dropped into a workflow without changing its control flow.
raise_onsets the severity at or above which a finding raises aValueErrorinstead: it fires on a high-severity finding, and stays quiet when the worst finding sits below the chosen level.try: aa.audit_leakage(df_seq, labels=labels, groups=groups, splits=splits_leaky, raise_on="high") except ValueError as e: print("ValueError:", str(e)[:300], "...")
ValueError: 'raise_on' ('high') matched 2 leakage finding(s) at or above that severity: same_protein_across_folds (high): 12 protein(s) have windows in both the training and the test part of fold(s) 0, 1, 2, 3, so neighbouring windows leak across the split; group_overlap_across_folds (high): 12 group(s) appear ...
# Only a medium finding here, so raise_on="high" stays quiet and just returns the table df_audit = aa.audit_leakage(df_dup, raise_on="high") print("status:", df_audit.attrs["status"], "-> no exception raised") # A clean setup never raises, whatever the threshold df_clean = df_seq.drop(columns=["sequence"]) print("clean status:", aa.audit_leakage(df_clean, raise_on="low").attrs["status"])
status: medium -> no exception raised clean status: ok
The audit is heuristic, and a clean report is not a proof that no leakage exists.
It inspects only the data and the folds it is given. It cannot see how a feature was built, whether a scaler was fitted before the split, or that two sequences are near-identical rather than byte-identical. Read
status='ok'as nothing obvious, not as a guarantee. The severities are labels for a human reader, not a machine taxonomy: whether a finding must block a workflow is a decision this package leaves to you.