|
| 1 | +__author__ = "satvshr" |
| 2 | +__all__ = ["Benchmarking"] |
| 3 | + |
| 4 | +import numpy as np |
| 5 | +import pandas as pd |
| 6 | +from sklearn.metrics import make_scorer |
| 7 | +from sklearn.model_selection import cross_validate |
| 8 | + |
| 9 | + |
| 10 | +class Benchmarking: |
| 11 | + """ |
| 12 | + Benchmark estimators using cross-validation. |
| 13 | +
|
| 14 | + You can: |
| 15 | +
|
| 16 | + - pass `X, y` (feature matrix and labels/targets) along with `cv` |
| 17 | + to use any cross-validation strategy; |
| 18 | + - if you want a fixed train/test split, pass a `PredefinedSplit` |
| 19 | + object as `cv`. |
| 20 | +
|
| 21 | + Parameters |
| 22 | + ---------- |
| 23 | + estimators : list[estimator] | estimator |
| 24 | + List of sklearn-like estimators implementing `fit` and `predict`. |
| 25 | + metrics : list[callable] | callable |
| 26 | + List of callables with signature `(y_true, y_pred) -> float`. |
| 27 | + X : array-like |
| 28 | + Feature matrix. |
| 29 | + y : array-like |
| 30 | + Target vector. |
| 31 | + cv : int, CV splitter, or None, default=None |
| 32 | + Cross-validation strategy. If `None`, defaults to 5-fold CV. |
| 33 | + If you want to use an explicit train/test split, pass a |
| 34 | + `PredefinedSplit` object. |
| 35 | +
|
| 36 | + Attributes |
| 37 | + ---------- |
| 38 | + results : pd.DataFrame |
| 39 | + DataFrame produced by :meth:`run`. |
| 40 | +
|
| 41 | + - Index: pandas.MultiIndex with two levels (names shown in parentheses) |
| 42 | + - level 0 "estimator": estimator name |
| 43 | + - level 1 "metric": evaluator name |
| 44 | + - Columns: ["train", "test"] (both floats) |
| 45 | + - Cell values: mean scores (float) computed across CV folds: |
| 46 | + - "train" = mean of cross_validate(...)[f"train_{metric}"] |
| 47 | + - "test" = mean of cross_validate(...)[f"test_{metric}"] |
| 48 | +
|
| 49 | + Example |
| 50 | + ------- |
| 51 | + >>> import numpy as np |
| 52 | + >>> from sklearn.metrics import accuracy_score |
| 53 | + >>> from sklearn.model_selection import PredefinedSplit |
| 54 | + >>> from pyaptamer.benchmarking._base import Benchmarking |
| 55 | + >>> from pyaptamer.aptanet import AptaNetPipeline |
| 56 | + >>> aptamer_seq = "AGCTTAGCGTACAGCTTAAAAGGGTTTCCCCTGCCCGCGTAC" |
| 57 | + >>> protein_seq = "ACDEFGHIKLMNPQRSTVWYACDEFGHIKLMNPQRSTVWY" |
| 58 | + >>> # dataset: 20 aptamer–protein pairs |
| 59 | + >>> X = [(aptamer_seq, protein_seq) for _ in range(20)] |
| 60 | + >>> y = np.array([0] * 10 + [1] * 10, dtype=np.float32) |
| 61 | + >>> clf = AptaNetPipeline(k=4) |
| 62 | + >>> # define a fixed train/test split |
| 63 | + >>> test_fold = np.ones(len(y)) * -1 |
| 64 | + >>> test_fold[-2:] = 0 |
| 65 | + >>> cv = PredefinedSplit(test_fold) |
| 66 | + >>> bench = Benchmarking( |
| 67 | + ... estimators=[clf], |
| 68 | + ... metrics=[accuracy_score], |
| 69 | + ... X=X, |
| 70 | + ... y=y, |
| 71 | + ... cv=cv, |
| 72 | + ... ) |
| 73 | + >>> summary = bench.run() # doctest: +SKIP |
| 74 | + """ |
| 75 | + |
| 76 | + def __init__(self, estimators, metrics, X, y, cv=None): |
| 77 | + self.estimators = estimators if isinstance(estimators, list) else [estimators] |
| 78 | + self.metrics = metrics if isinstance(metrics, list) else [metrics] |
| 79 | + self.X = X |
| 80 | + self.y = y |
| 81 | + self.cv = cv |
| 82 | + self.results = None |
| 83 | + |
| 84 | + def _to_scorers(self, metrics): |
| 85 | + """Convert metric callables to a dict of scorers.""" |
| 86 | + scorers = {} |
| 87 | + for metric in metrics: |
| 88 | + if not callable(metric): |
| 89 | + raise ValueError("Each metric should be a callable.") |
| 90 | + name = ( |
| 91 | + metric.__name__ |
| 92 | + if hasattr(metric, "__name__") |
| 93 | + else metric.__class__.__name__ |
| 94 | + ) |
| 95 | + scorers[name] = make_scorer(metric) |
| 96 | + return scorers |
| 97 | + |
| 98 | + def _to_df(self, results): |
| 99 | + """Convert nested results to a unified DataFrame.""" |
| 100 | + records = [] |
| 101 | + index = [] |
| 102 | + |
| 103 | + for est_name, est_scores in results.items(): |
| 104 | + for metric_name, scores in est_scores.items(): |
| 105 | + records.append(scores) |
| 106 | + index.append((est_name, metric_name)) |
| 107 | + |
| 108 | + index = pd.MultiIndex.from_tuples(index, names=["estimator", "metric"]) |
| 109 | + return pd.DataFrame(records, index=index, columns=["train", "test"]) |
| 110 | + |
| 111 | + def run(self): |
| 112 | + """ |
| 113 | + Train each estimator and evaluate with cross-validation. |
| 114 | +
|
| 115 | + Returns |
| 116 | + ------- |
| 117 | + results : pd.DataFrame |
| 118 | +
|
| 119 | + - Index: pandas.MultiIndex with two levels (names shown in parentheses) |
| 120 | + - level 0 "estimator": estimator name |
| 121 | + - level 1 "metric": evaluator name |
| 122 | + - Columns: ["train", "test"] (both floats) |
| 123 | + - Cell values: mean scores (float) computed across CV folds: |
| 124 | + - "train" = mean of cross_validate(...)[f"train_{metric}"] |
| 125 | + - "test" = mean of cross_validate(...)[f"test_{metric}"] |
| 126 | +
|
| 127 | + """ |
| 128 | + self.scorers_ = self._to_scorers(self.metrics) |
| 129 | + results = {} |
| 130 | + |
| 131 | + for estimator in self.estimators: |
| 132 | + est_name = estimator.__class__.__name__ |
| 133 | + |
| 134 | + cv_results = cross_validate( |
| 135 | + estimator, |
| 136 | + self.X, |
| 137 | + self.y, |
| 138 | + cv=self.cv, |
| 139 | + scoring=self.scorers_, |
| 140 | + return_train_score=True, |
| 141 | + ) |
| 142 | + |
| 143 | + # average across folds |
| 144 | + est_scores = {} |
| 145 | + for metric in self.scorers_.keys(): |
| 146 | + est_scores[metric] = { |
| 147 | + "train": float(np.mean(cv_results[f"train_{metric}"])), |
| 148 | + "test": float(np.mean(cv_results[f"test_{metric}"])), |
| 149 | + } |
| 150 | + |
| 151 | + results[est_name] = est_scores |
| 152 | + |
| 153 | + self.results = self._to_df(results) |
| 154 | + return self.results |
0 commit comments