AAPred.eval
- AAPred.eval(X, labels, *, X_holdout=None, labels_holdout=None, metrics=None, n_cv=5, cv=None, df_seq=None, baseline=None, list_parts=None)[source]
Evaluate every model across metrics by cross-validation and an optional held-out set.
Up to three evaluation principles are reported:
cv(stratified k-fold cross-validation onX, scored per fold then averaged) and, when a held-out set is provided,holdout(models fit onXand scored onX_holdout). The result is a long-format table with one row per (model, metric, principle).Pass
cvto cross-validate with an arbitrary scikit-learn splitter (e.g.LeaveOneOut()) instead of the integern_cvfolds. The splitter is not capped at the smallest class count, and its rows are scored by thecv_pooledprinciple: every held-out prediction is pooled and each metric is applied once on that pooled vector (reproducingmetric(labels, cross_val_predict(estimator, X, labels, cv=cv))), rather than averaging a per-fold score. This is the correct principle forLeaveOneOuton a small, imbalanced set, where a single-sample test fold makes per-fold averaging degenerate.Set
baselineto compare the bound features against simple, non-positional baseline featurizers (amino-acid / dipeptide / scale composition) built internally fromdf_seq: each baseline is cross-validated with the same models and folds and its rows are appended, so the whole “CPP vs baseline” comparison comes from one call. This quantifies how much the positional CPP features add over a plain composition encoding.Added in version 1.1.0.
- Parameters:
X (array-like, shape (n_samples, n_features)) – Feature matrix used for cross-validation (and, for the holdout principle, training).
labels (array-like, shape (n_samples,)) – Class labels for samples in
X.X_holdout (array-like, shape (n_holdout, n_features), optional) – Held-out feature matrix. If given, the
holdoutprinciple is added.labels_holdout (array-like, shape (n_holdout,), optional) – Class labels for
X_holdout. Required ifX_holdoutis given.metrics (list of str, optional) –
Performance metrics to compute, each one of
accuracy,balanced_accuracy,precision,recall,f1,roc_auc, andmcc(Matthews correlation coefficient). Defaults tolist_metricsfrom the constructor.Changed in version 1.2.0:
mcc(Matthews correlation coefficient) is accepted.n_cv (int, default=5) – Number of stratified cross-validation folds (must not exceed the smallest class count). Ignored when
cvis given.cv (cross-validation splitter, optional) – A scikit-learn cross-validation splitter exposing a
splitmethod (e.g.LeaveOneOut(),StratifiedKFold(n_splits=10)). When given, it replaces the integern_cvfolds and the cross-validation rows are scored by the pooledcv_pooledprinciple (each metric applied once on the pooled out-of-fold predictions, soscore_stdisNaN). Not capped at the smallest class count.df_seq (pd.DataFrame, shape (n_samples, n_seq_info), optional) – DataFrame containing an
entrycolumn with unique protein identifiers and sequence information (the same input accepted bySequenceFeature.get_df_parts()). Must be row-aligned withX/labels(row i is the same sample) and built with the same part geometry asXfor a fair comparison — the alignment cannot be verified from the opaqueX, onlylen(df_seq) == len(labels)is checked. Required whenbaselineis set, ignored otherwise.baseline (bool, str, or list of str, optional) – Baseline featurizer(s) to cross-validate alongside the bound features.
Trueuses the scale-composition baseline ('scale'); a str or list selects among'scale'(SequenceFeature.scale_composition()),'aac'(SequenceFeature.aa_composition()),'dpc'(SequenceFeature.dipeptide_composition()), and'acc'(SequenceFeature.acc(), the order-aware scale auto-covariance).None(default) adds no baseline. Baselines coverlist_partswithSequenceFeature.get_df_parts()’ default JMD lengths; match the geometry used to buildXso the comparison is not confounded.list_parts (str or list of str, optional) – Sequence parts averaged into each baseline (passed to the featurizers). Defaults to the whole
tmd_jmdspan. Used only whenbaselineis set.
- Returns:
df_eval – Long-format evaluation table with columns
model,metric,principle,score, andscore_std. Theprincipleiscvfor the default per-fold cross-validation,cv_pooledwhen acvsplitter is passed, andholdoutfor the held-out set;score_stdisNaNfor theholdoutandcv_pooledprinciples (each is a single estimate). Whenbaselineis given, a leadingfeaturescolumn is added ('cpp'for the bound-feature rows, the baseline kind for each baseline’s cross-validation rows); withbaseline=Nonethe table is unchanged (5 columns).- Return type:
pd.DataFrame, shape (n_rows, 5) — or (n_rows, 6) in baseline mode
- Raises:
ValueError – If feature or label inputs are invalid or misaligned, a metric, splitter,
n_cv,list_parts, or baseline selection is invalid, a probability metric is requested from an estimator withoutpredict_proba, or a held-out input is incomplete or has a different feature count.
Examples
To demonstrate
AAPred().eval(), we obtain theDOM_GSECdataset and its feature matrix:import aaanalysis as aa aa.options["verbose"] = False # Disable verbosity # DOM_GSEC example dataset + its feature set (see [Breimann25]_) df_seq = aa.load_dataset(name="DOM_GSEC") labels = df_seq["label"].to_list() df_feat = aa.load_features(name="DOM_GSEC").head(20) # Build the CPP feature matrix sf = aa.SequenceFeature() df_parts = sf.get_df_parts(df_seq=df_seq) X = sf.feature_matrix(features=df_feat["feature"], df_parts=df_parts)
evalscores every model across metrics by stratified cross-validation and returns a long-format table (one row per model, metric, and evaluation principle):aap = aa.AAPred(random_state=42) df_eval = aap.eval(X, labels) aa.display_df(df_eval, n_rows=10, show_shape=True)
DataFrame shape: (4, 5)
model metric principle score score_std 1 RandomForestClassifier accuracy cv 0.809231 0.064659 2 RandomForestClassifier balanced_accuracy cv 0.810256 0.065416 3 RandomForestClassifier f1 cv 0.810256 0.059252 4 RandomForestClassifier roc_auc cv 0.887278 0.071059 Providing a held-out set adds the
holdoutprinciple beside cross-validation (score_stdisNaNfor the single held-out estimate):from sklearn.model_selection import train_test_split X_tr, X_ho, y_tr, y_ho = train_test_split(X, labels, test_size=0.3, random_state=0, stratify=labels) df_eval = aap.eval(X_tr, y_tr, X_holdout=X_ho, labels_holdout=y_ho) aa.display_df(df_eval, n_rows=10, show_shape=True)
DataFrame shape: (8, 5)
model metric principle score score_std 1 RandomForestClassifier accuracy cv 0.806536 0.105052 2 RandomForestClassifier accuracy holdout 0.842105 nan 3 RandomForestClassifier balanced_accuracy cv 0.808333 0.105556 4 RandomForestClassifier balanced_accuracy holdout 0.842105 nan 5 RandomForestClassifier f1 cv 0.800611 0.117547 6 RandomForestClassifier f1 holdout 0.833333 nan 7 RandomForestClassifier roc_auc cv 0.916667 0.078567 8 RandomForestClassifier roc_auc holdout 0.896122 nan The metrics and number of cross-validation folds are controlled by
metricsandn_cv. Besidesaccuracy,balanced_accuracy,precision,recall,f1, androc_auc, the metric vocabulary includesmcc(Matthews correlation coefficient), a balanced single-number summary of the confusion matrix that ranges from -1 to 1:df_eval = aap.eval(X, labels, metrics=["balanced_accuracy", "roc_auc", "mcc"], n_cv=3) aa.display_df(df_eval, n_rows=10, show_shape=True)
DataFrame shape: (3, 5)
model metric principle score score_std 1 RandomForestClassifier balanced_accuracy cv 0.793651 0.059391 2 RandomForestClassifier roc_auc cv 0.863190 0.061409 3 RandomForestClassifier mcc cv 0.596243 0.123690 Pass
cvto cross-validate with an arbitrary scikit-learn splitter, such asLeaveOneOutfor a small, imbalanced set where the integern_cvfolds would be capped at the smallest class count. The splitter is not capped, and each metric is scored once on the pooled out-of-fold predictions (thecv_pooledprinciple, soscore_stdisNaN), reproducingbalanced_accuracy_score(labels, cross_val_predict(estimator, X, labels, cv=cv)):from sklearn.model_selection import LeaveOneOut df_eval = aap.eval(X, labels, cv=LeaveOneOut(), metrics=["balanced_accuracy"]) aa.display_df(df_eval, n_rows=10, show_shape=True)
DataFrame shape: (1, 5)
model metric principle score score_std 1 RandomForestClassifier balanced_accuracy cv_pooled 0.825397 nan Set
baselineto compare the CPP features against simple, non-positional composition baselines built internally fromdf_seq—scale(scale-average),aac(amino-acid composition), anddpc(dipeptide composition), each averaged overlist_parts. Every baseline is cross-validated with the same models and folds, and the rows are tagged in a leadingfeaturescolumn (cppfor the bound features), so the whole “CPP vs baseline” comparison comes from one call:df_eval = aap.eval(X, labels, df_seq=df_seq, baseline=["scale", "aac", "dpc"], list_parts="tmd_jmd") aa.display_df(df_eval, n_rows=10, show_shape=True)
DataFrame shape: (16, 6)
features model metric principle score score_std 1 cpp RandomForestClassifier accuracy cv 0.809231 0.064659 2 cpp RandomForestClassifier balanced_accuracy cv 0.810256 0.065416 3 cpp RandomForestClassifier f1 cv 0.810256 0.059252 4 cpp RandomForestClassifier roc_auc cv 0.887278 0.071059 5 scale RandomForestClassifier accuracy cv 0.754462 0.094264 6 scale RandomForestClassifier balanced_accuracy cv 0.757051 0.095218 7 scale RandomForestClassifier f1 cv 0.749096 0.093903 8 scale RandomForestClassifier roc_auc cv 0.845217 0.075511 9 aac RandomForestClassifier accuracy cv 0.706154 0.090286 10 aac RandomForestClassifier balanced_accuracy cv 0.706410 0.091143