Download src/feature_selection.py from zaaabik/paper_extraction: direct link, hf CLI and curl.
- Browser
- Download file 6.31 kB
-
https://huggingface.co/datasets/zaaabik/paper_extraction/resolve/main/src/feature_selection.py
- Command line
-
hf download hf://datasets/zaaabik/paper_extraction/src/feature_selection.py
-
curl -L -o feature_selection.py https://huggingface.co/datasets/zaaabik/paper_extraction/resolve/main/src/feature_selection.py
6.31 kB
| """Feature selection strategies for the error predictor. | |
| Strategies: | |
| 1. ``rank_by_roc_auc`` — univariate ROC-AUC ranking against the | |
| "model is wrong" label. | |
| 2. ``greedy_forward_select`` — TOHA-style Algorithm 1: greedy forward CV-AUC. | |
| 3. ``top_k_per_group`` — paper-faithful "up to K of each type" using | |
| univariate ranking inside each group. | |
| 4. ``shapley_top_k_per_group`` — **paper-faithful**: fit a logistic regression | |
| on the wrongness label, compute exact Shapley values for it via | |
| ``shap.LinearExplainer``, then keep top-K per group by mean |Shapley|. | |
| """ | |
| from __future__ import annotations | |
| from typing import List, Tuple | |
| import numpy as np | |
| from sklearn.linear_model import LogisticRegression | |
| from sklearn.model_selection import StratifiedKFold | |
| from sklearn.metrics import roc_auc_score | |
| from sklearn.preprocessing import StandardScaler | |
| from tqdm import tqdm | |
| def _safe_auc(y_true: np.ndarray, score: np.ndarray) -> float: | |
| if len(np.unique(y_true)) < 2: | |
| return 0.5 | |
| # Higher score should mean "more likely to be wrong". | |
| return float(roc_auc_score(y_true, score)) | |
| def rank_by_roc_auc(X: np.ndarray, y_wrong: np.ndarray) -> np.ndarray: | |
| """Return per-feature ROC-AUC scores (vs the better of feature/feature-negated).""" | |
| n_features = X.shape[1] | |
| scores = np.zeros(n_features, dtype=np.float32) | |
| for j in range(n_features): | |
| v = X[:, j] | |
| auc_pos = _safe_auc(y_wrong, v) | |
| auc_neg = _safe_auc(y_wrong, -v) | |
| scores[j] = max(auc_pos, auc_neg) | |
| return scores | |
| def top_k_by_univariate_auc(X: np.ndarray, y_wrong: np.ndarray, k: int) -> List[int]: | |
| scores = rank_by_roc_auc(X, y_wrong) | |
| order = np.argsort(scores)[::-1] | |
| return order[:k].tolist() | |
| def shapley_top_k_per_group( | |
| X: np.ndarray, | |
| y_wrong: np.ndarray, | |
| group_of: List[str], | |
| k_per_group: dict, | |
| *, | |
| random_state: int = 42, | |
| nsamples_background: int = 100, | |
| ) -> List[int]: | |
| """Paper-faithful Shapley-based feature selection. | |
| Train a logistic regression on the binary wrongness target, then use | |
| ``shap.LinearExplainer`` (exact Shapley values for linear models, O(N·F)) | |
| to obtain per-sample contributions. Score each feature by mean absolute | |
| Shapley value. Keep the top-K within each named group. | |
| """ | |
| import shap | |
| from sklearn.linear_model import LogisticRegression | |
| from sklearn.preprocessing import StandardScaler | |
| assert len(group_of) == X.shape[1], (len(group_of), X.shape[1]) | |
| scaler = StandardScaler() | |
| Xs = scaler.fit_transform(X).astype(np.float32) | |
| clf = LogisticRegression(max_iter=2000, n_jobs=1, solver="lbfgs", random_state=random_state) | |
| clf.fit(Xs, y_wrong) | |
| bg = shap.sample(Xs, min(nsamples_background, Xs.shape[0]), random_state=random_state) | |
| explainer = shap.LinearExplainer(clf, bg, feature_perturbation="interventional") | |
| shap_values = explainer.shap_values(Xs) # (N, F) | |
| importance = np.abs(shap_values).mean(axis=0) # (F,) | |
| selected: List[int] = [] | |
| by_group: dict = {} | |
| for i, g in enumerate(group_of): | |
| by_group.setdefault(g, []).append(i) | |
| for g, idx_list in by_group.items(): | |
| k = k_per_group.get(g, len(idx_list)) | |
| if k >= len(idx_list): | |
| selected.extend(idx_list) | |
| continue | |
| scores = importance[idx_list] | |
| order = np.argsort(scores)[::-1][:k] | |
| selected.extend([idx_list[j] for j in order]) | |
| return sorted(selected) | |
| def top_k_per_group( | |
| X: np.ndarray, | |
| y_wrong: np.ndarray, | |
| group_of: List[str], | |
| k_per_group: dict, | |
| ) -> List[int]: | |
| """Per-group univariate top-K selection. | |
| Args: | |
| X: (N, F) feature matrix. | |
| y_wrong: (N,) binary target. | |
| group_of: list of length F naming each column's group ("ripser", "cb", …). | |
| k_per_group: dict {group_name: int}. Groups not in the dict keep all columns. | |
| Returns: | |
| Sorted list of selected column indices. | |
| """ | |
| assert len(group_of) == X.shape[1], (len(group_of), X.shape[1]) | |
| selected: List[int] = [] | |
| by_group: dict = {} | |
| for i, g in enumerate(group_of): | |
| by_group.setdefault(g, []).append(i) | |
| for g, idx_list in by_group.items(): | |
| k = k_per_group.get(g, len(idx_list)) | |
| if k >= len(idx_list): | |
| selected.extend(idx_list) | |
| continue | |
| Xg = X[:, idx_list] | |
| scores = rank_by_roc_auc(Xg, y_wrong) | |
| order = np.argsort(scores)[::-1][:k] | |
| selected.extend([idx_list[j] for j in order]) | |
| return sorted(selected) | |
| def greedy_forward_select( | |
| X: np.ndarray, | |
| y_wrong: np.ndarray, | |
| *, | |
| max_features: int = 30, | |
| min_gain: float = 1e-3, | |
| cv_folds: int = 5, | |
| candidate_pool: List[int] | None = None, | |
| random_state: int = 0, | |
| ) -> Tuple[List[int], List[float]]: | |
| """TOHA-style Algorithm 1.""" | |
| pool = list(range(X.shape[1])) if candidate_pool is None else list(candidate_pool) | |
| selected: List[int] = [] | |
| history: List[float] = [] | |
| best_auc = 0.5 | |
| # Standardize once up front so the inner LogReg converges quickly. | |
| Xz = StandardScaler().fit_transform(X).astype(np.float32) | |
| skf = StratifiedKFold(n_splits=cv_folds, shuffle=True, random_state=random_state) | |
| pbar = tqdm(total=max_features, desc="TOHA-greedy") | |
| while pool and len(selected) < max_features: | |
| best_j, best_step_auc = -1, best_auc | |
| for j in pool: | |
| cols = selected + [j] | |
| Xs = Xz[:, cols] | |
| fold_aucs = [] | |
| for tr, va in skf.split(Xs, y_wrong): | |
| clf = LogisticRegression(max_iter=2000, n_jobs=1, solver="lbfgs") | |
| clf.fit(Xs[tr], y_wrong[tr]) | |
| proba = clf.predict_proba(Xs[va])[:, 1] | |
| fold_aucs.append(_safe_auc(y_wrong[va], proba)) | |
| mean_auc = float(np.mean(fold_aucs)) | |
| if mean_auc > best_step_auc: | |
| best_step_auc = mean_auc | |
| best_j = j | |
| if best_j == -1 or (best_step_auc - best_auc) < min_gain: | |
| break | |
| selected.append(best_j) | |
| pool.remove(best_j) | |
| history.append(best_step_auc) | |
| pbar.update(1) | |
| pbar.set_postfix(auc=f"{best_step_auc:.4f}", picked=best_j) | |
| best_auc = best_step_auc | |
| pbar.close() | |
| return selected, history | |