File size: 6,310 Bytes
2eb3475
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""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