File size: 7,599 Bytes
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
from __future__ import annotations

from dataclasses import dataclass
from typing import Dict, List, Optional

import numpy as np
from sklearn.ensemble import RandomForestRegressor

try:
    from xgboost import XGBRegressor
except Exception:  # pragma: no cover
    XGBRegressor = None  # type: ignore[assignment]


@dataclass
class SurrogateConfig:
    prefer_xgboost: bool = True
    random_state: int = 42
    n_estimators: int = 200
    min_train_samples: int = 8
    max_depth_small: int = 3
    max_depth_large: int = 6


class SurrogateModel:
    """Surrogate model with explicit missing-feature masking support."""

    def __init__(self, config: Optional[SurrogateConfig] = None):
        self.config = config or SurrogateConfig()
        self.model = None
        self.backend = "uninitialized"
        self.feature_names: List[str] = []
        self.mask_names: List[str] = []

        self._median: np.ndarray | None = None
        self._iqr: np.ndarray | None = None
        self._train_x: np.ndarray | None = None
        self._train_y: np.ndarray | None = None
        self.last_fit_stats: Dict[str, float] = {}

    def _build_model(self, n_samples: int):
        max_depth = self.config.max_depth_small if n_samples < 50 else self.config.max_depth_large
        if self.config.prefer_xgboost and XGBRegressor is not None:
            self.backend = "xgboost"
            return XGBRegressor(
                n_estimators=self.config.n_estimators,
                max_depth=max_depth,
                learning_rate=0.05,
                subsample=0.9,
                colsample_bytree=0.9,
                reg_alpha=0.1,
                reg_lambda=1.0,
                random_state=self.config.random_state,
            )

        self.backend = "random_forest"
        return RandomForestRegressor(
            n_estimators=max(100, self.config.n_estimators),
            max_depth=max_depth,
            random_state=self.config.random_state,
            n_jobs=-1,
        )

    def _fit_normalizer(self, x: np.ndarray, m: np.ndarray) -> None:
        med = []
        iqr = []
        for j in range(x.shape[1]):
            vals = x[m[:, j] > 0.5, j]
            if vals.size == 0:
                med.append(0.0)
                iqr.append(1.0)
                continue
            q1 = float(np.quantile(vals, 0.25))
            q3 = float(np.quantile(vals, 0.75))
            inter = max(1e-6, q3 - q1)
            med.append(float(np.median(vals)))
            iqr.append(inter)
        self._median = np.asarray(med, dtype=float)
        self._iqr = np.asarray(iqr, dtype=float)

    def _transform(self, x: np.ndarray, m: np.ndarray, fit: bool = False) -> np.ndarray:
        x = np.asarray(x, dtype=float)
        m = np.asarray(m, dtype=float)
        if fit or self._median is None or self._iqr is None:
            self._fit_normalizer(x, m)
        assert self._median is not None and self._iqr is not None

        x_filled = np.where(np.isfinite(x), x, np.nan)
        for j in range(x.shape[1]):
            col = x_filled[:, j]
            missing = ~np.isfinite(col)
            col[missing] = self._median[j]
            x_filled[:, j] = (col - self._median[j]) / self._iqr[j]

        # Explicit missingness information: concatenate mask vector.
        return np.concatenate([x_filled, m], axis=1)

    def fit(
        self,
        features: np.ndarray,
        masks: np.ndarray,
        y: np.ndarray,
        feature_names: List[str],
        mask_names: List[str],
    ) -> Dict[str, float]:
        y = np.asarray(y, dtype=float)
        valid = np.isfinite(y)
        n_samples = int(np.sum(valid))

        self.feature_names = list(feature_names)
        self.mask_names = list(mask_names)

        if n_samples < self.config.min_train_samples:
            self.model = None
            self.backend = "warmup"
            self.last_fit_stats = {
                "n_train": float(n_samples),
                "train_mae": np.nan,
                "val_mae": np.nan,
                "instability_ratio": 1.0,
            }
            return self.last_fit_stats

        x = np.asarray(features, dtype=float)[valid]
        m = np.asarray(masks, dtype=float)[valid]
        yv = y[valid]

        x_trans = self._transform(x, m, fit=True)
        self._train_x = x_trans
        self._train_y = yv

        self.model = self._build_model(n_samples=n_samples)
        self.model.fit(x_trans, yv)

        train_pred = self.model.predict(x_trans)
        train_mae = float(np.mean(np.abs(train_pred - yv)))

        # Simple rolling validation proxy.
        if n_samples >= 12:
            split = int(max(8, n_samples * 0.8))
            x_tr, x_val = x_trans[:split], x_trans[split:]
            y_tr, y_val = yv[:split], yv[split:]

            val_model = self._build_model(n_samples=split)
            val_model.fit(x_tr, y_tr)
            val_pred = val_model.predict(x_val)
            val_mae = float(np.mean(np.abs(val_pred - y_val))) if y_val.size else train_mae
        else:
            val_mae = train_mae

        instability = float((val_mae + 1e-6) / (train_mae + 1e-6))
        self.last_fit_stats = {
            "n_train": float(n_samples),
            "train_mae": train_mae,
            "val_mae": val_mae,
            "instability_ratio": instability,
        }
        return self.last_fit_stats

    def _rf_uncertainty(self, x: np.ndarray) -> np.ndarray:
        assert self.model is not None
        if not hasattr(self.model, "estimators_"):
            return np.full(x.shape[0], float(np.std(self._train_y)) if self._train_y is not None else 1.0)
        preds = np.vstack([tree.predict(x) for tree in self.model.estimators_])
        return np.std(preds, axis=0)

    def predict_bundle(self, features: np.ndarray, masks: np.ndarray, topk_threshold: float | None = None) -> Dict[str, np.ndarray]:
        n = features.shape[0]
        if self.model is None:
            return {
                "expected_score": np.zeros(n, dtype=float),
                "topk_probability": np.full(n, 0.5, dtype=float),
                "uncertainty": np.full(n, 1.0, dtype=float),
            }

        x = self._transform(np.asarray(features, dtype=float), np.asarray(masks, dtype=float), fit=False)
        expected = self.model.predict(x)

        if self.backend == "random_forest":
            uncertainty = self._rf_uncertainty(x)
        else:
            residual_scale = (
                float(np.std(self._train_y - self.model.predict(self._train_x)))
                if self._train_x is not None and self._train_y is not None
                else 1.0
            )
            uncertainty = np.full(expected.shape[0], max(1e-3, residual_scale))

        if topk_threshold is None:
            topk_threshold = float(np.quantile(self._train_y, 0.8)) if self._train_y is not None else 0.0

        z = (expected - topk_threshold) / (uncertainty + 1e-6)
        topk_prob = 1.0 / (1.0 + np.exp(-z))
        return {
            "expected_score": expected.astype(float),
            "topk_probability": topk_prob.astype(float),
            "uncertainty": uncertainty.astype(float),
        }

    def feature_importance(self) -> Dict[str, float]:
        if self.model is None or not hasattr(self.model, "feature_importances_"):
            return {}

        names = self.feature_names + self.mask_names
        importances = np.asarray(self.model.feature_importances_, dtype=float)
        if importances.size != len(names):
            return {}
        return {name: float(value) for name, value in zip(names, importances)}