| 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: |
| XGBRegressor = None |
|
|
|
|
| @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] |
|
|
| |
| 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))) |
|
|
| |
| 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)} |
|
|