|
| 1 | +"""Nuisance-model quality diagnostics for behavior and outcome models.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from dataclasses import dataclass, field |
| 6 | +from typing import Optional, Sequence |
| 7 | + |
| 8 | +import numpy as np |
| 9 | +import pandas as pd |
| 10 | +from sklearn.metrics import brier_score_loss, log_loss, mean_absolute_error, mean_squared_error, r2_score, roc_auc_score |
| 11 | + |
| 12 | +from policyscope.estimators import mu_hat_predict |
| 13 | +from policyscope.nuisance import ( |
| 14 | + BehaviorPredictions, |
| 15 | + CrossFitNuisanceBundle, |
| 16 | + OutcomePredictions, |
| 17 | + fit_outcome_nuisance_bundle, |
| 18 | +) |
| 19 | + |
| 20 | + |
| 21 | +@dataclass(frozen=True) |
| 22 | +class BehaviorModelDiagnostics: |
| 23 | + applicable: bool |
| 24 | + propensity_source: str |
| 25 | + is_out_of_fold: bool |
| 26 | + multiclass_log_loss: Optional[float] = None |
| 27 | + top1_accuracy: Optional[float] = None |
| 28 | + mean_logged_action_prob: Optional[float] = None |
| 29 | + warnings: tuple[str, ...] = field(default_factory=tuple) |
| 30 | + |
| 31 | + def to_dict(self) -> dict: |
| 32 | + return { |
| 33 | + "applicable": self.applicable, |
| 34 | + "propensity_source": self.propensity_source, |
| 35 | + "is_out_of_fold": self.is_out_of_fold, |
| 36 | + "multiclass_log_loss": self.multiclass_log_loss, |
| 37 | + "top1_accuracy": self.top1_accuracy, |
| 38 | + "mean_logged_action_prob": self.mean_logged_action_prob, |
| 39 | + "warnings": list(self.warnings), |
| 40 | + } |
| 41 | + |
| 42 | + |
| 43 | +@dataclass(frozen=True) |
| 44 | +class OutcomeModelDiagnostics: |
| 45 | + applicable: bool |
| 46 | + target: str |
| 47 | + is_binary_target: bool |
| 48 | + is_out_of_fold: bool |
| 49 | + log_loss: Optional[float] = None |
| 50 | + brier_score: Optional[float] = None |
| 51 | + roc_auc: Optional[float] = None |
| 52 | + rmse: Optional[float] = None |
| 53 | + mae: Optional[float] = None |
| 54 | + r2: Optional[float] = None |
| 55 | + warnings: tuple[str, ...] = field(default_factory=tuple) |
| 56 | + |
| 57 | + def to_dict(self) -> dict: |
| 58 | + return { |
| 59 | + "applicable": self.applicable, |
| 60 | + "target": self.target, |
| 61 | + "is_binary_target": self.is_binary_target, |
| 62 | + "is_out_of_fold": self.is_out_of_fold, |
| 63 | + "log_loss": self.log_loss, |
| 64 | + "brier_score": self.brier_score, |
| 65 | + "roc_auc": self.roc_auc, |
| 66 | + "rmse": self.rmse, |
| 67 | + "mae": self.mae, |
| 68 | + "r2": self.r2, |
| 69 | + "warnings": list(self.warnings), |
| 70 | + } |
| 71 | + |
| 72 | + |
| 73 | +@dataclass(frozen=True) |
| 74 | +class NuisanceDiagnostics: |
| 75 | + behavior: BehaviorModelDiagnostics |
| 76 | + outcome: OutcomeModelDiagnostics |
| 77 | + warnings: tuple[str, ...] = field(default_factory=tuple) |
| 78 | + |
| 79 | + def to_dict(self) -> dict: |
| 80 | + return { |
| 81 | + "behavior": self.behavior.to_dict(), |
| 82 | + "outcome": self.outcome.to_dict(), |
| 83 | + "warnings": list(self.warnings), |
| 84 | + } |
| 85 | + |
| 86 | + |
| 87 | +def _compute_behavior_diagnostics( |
| 88 | + df: pd.DataFrame, |
| 89 | + *, |
| 90 | + action_col: str, |
| 91 | + behavior_predictions: Optional[BehaviorPredictions], |
| 92 | + propensity_source: Optional[str], |
| 93 | +) -> BehaviorModelDiagnostics: |
| 94 | + if behavior_predictions is None or propensity_source not in {"estimated", "auto"}: |
| 95 | + return BehaviorModelDiagnostics( |
| 96 | + applicable=False, |
| 97 | + propensity_source=propensity_source or "unknown", |
| 98 | + is_out_of_fold=False, |
| 99 | + warnings=("behavior_model_not_applicable_for_logged_propensity",), |
| 100 | + ) |
| 101 | + |
| 102 | + y = df[action_col].to_numpy() |
| 103 | + p_taken = np.clip(behavior_predictions.pA_taken, 1e-12, 1.0) |
| 104 | + ll = float(-np.mean(np.log(p_taken))) |
| 105 | + top1 = None |
| 106 | + if behavior_predictions.pA_all is not None: |
| 107 | + top1 = float(np.mean(np.argmax(behavior_predictions.pA_all, axis=1) == y)) |
| 108 | + warnings: list[str] = [] |
| 109 | + if ll > 1.2: |
| 110 | + warnings.append("weak_behavior_log_loss") |
| 111 | + if top1 is not None and top1 < 0.4: |
| 112 | + warnings.append("weak_behavior_top1_accuracy") |
| 113 | + |
| 114 | + return BehaviorModelDiagnostics( |
| 115 | + applicable=True, |
| 116 | + propensity_source=propensity_source or behavior_predictions.propensity_source or "estimated", |
| 117 | + is_out_of_fold=bool(behavior_predictions.is_out_of_fold), |
| 118 | + multiclass_log_loss=ll, |
| 119 | + top1_accuracy=top1, |
| 120 | + mean_logged_action_prob=float(np.mean(p_taken)), |
| 121 | + warnings=tuple(warnings), |
| 122 | + ) |
| 123 | + |
| 124 | + |
| 125 | +def _compute_outcome_diagnostics( |
| 126 | + df: pd.DataFrame, |
| 127 | + *, |
| 128 | + target: str, |
| 129 | + feature_cols: Optional[Sequence[str]], |
| 130 | + action_col: str, |
| 131 | + estimator: str, |
| 132 | + outcome_predictions: Optional[OutcomePredictions], |
| 133 | +) -> OutcomeModelDiagnostics: |
| 134 | + if estimator not in {"dm", "dr", "sndr", "switch_dr"}: |
| 135 | + return OutcomeModelDiagnostics( |
| 136 | + applicable=False, |
| 137 | + target=target, |
| 138 | + is_binary_target=False, |
| 139 | + is_out_of_fold=False, |
| 140 | + warnings=("outcome_model_not_used_for_estimator",), |
| 141 | + ) |
| 142 | + |
| 143 | + y = df[target].to_numpy() |
| 144 | + is_binary = np.array_equal(np.unique(y), np.array([0, 1])) or np.array_equal(np.unique(y), np.array([0.0, 1.0])) |
| 145 | + |
| 146 | + if outcome_predictions is None: |
| 147 | + mu_bundle = fit_outcome_nuisance_bundle(df, target=target, feature_cols=feature_cols, action_col=action_col) |
| 148 | + pred = mu_hat_predict(mu_bundle.mu_model, df, df[action_col].to_numpy(), target) |
| 149 | + is_oof = False |
| 150 | + else: |
| 151 | + pred = outcome_predictions.mu_logged_action |
| 152 | + is_oof = bool(outcome_predictions.is_out_of_fold) |
| 153 | + |
| 154 | + warnings: list[str] = [] |
| 155 | + if is_binary: |
| 156 | + p = np.clip(pred, 1e-12, 1 - 1e-12) |
| 157 | + ll = float(log_loss(y, p, labels=[0, 1])) |
| 158 | + br = float(brier_score_loss(y, p)) |
| 159 | + try: |
| 160 | + auc = float(roc_auc_score(y, p)) |
| 161 | + except ValueError: |
| 162 | + auc = None |
| 163 | + if ll > 0.69: |
| 164 | + warnings.append("weak_outcome_log_loss") |
| 165 | + if br > 0.25: |
| 166 | + warnings.append("weak_outcome_brier") |
| 167 | + if auc is not None and auc < 0.6: |
| 168 | + warnings.append("weak_outcome_auc") |
| 169 | + return OutcomeModelDiagnostics( |
| 170 | + applicable=True, |
| 171 | + target=target, |
| 172 | + is_binary_target=True, |
| 173 | + is_out_of_fold=is_oof, |
| 174 | + log_loss=ll, |
| 175 | + brier_score=br, |
| 176 | + roc_auc=auc, |
| 177 | + warnings=tuple(warnings), |
| 178 | + ) |
| 179 | + |
| 180 | + rmse = float(np.sqrt(mean_squared_error(y, pred))) |
| 181 | + mae = float(mean_absolute_error(y, pred)) |
| 182 | + r2 = float(r2_score(y, pred)) |
| 183 | + if r2 < 0.0: |
| 184 | + warnings.append("weak_outcome_r2") |
| 185 | + return OutcomeModelDiagnostics( |
| 186 | + applicable=True, |
| 187 | + target=target, |
| 188 | + is_binary_target=False, |
| 189 | + is_out_of_fold=is_oof, |
| 190 | + rmse=rmse, |
| 191 | + mae=mae, |
| 192 | + r2=r2, |
| 193 | + warnings=tuple(warnings), |
| 194 | + ) |
| 195 | + |
| 196 | + |
| 197 | +def compute_nuisance_diagnostics( |
| 198 | + df: pd.DataFrame, |
| 199 | + *, |
| 200 | + target: str, |
| 201 | + estimator: str, |
| 202 | + feature_cols: Optional[Sequence[str]], |
| 203 | + action_col: str, |
| 204 | + propensity_source: Optional[str], |
| 205 | + behavior_predictions: Optional[BehaviorPredictions] = None, |
| 206 | + nuisance_bundle: Optional[CrossFitNuisanceBundle] = None, |
| 207 | +) -> NuisanceDiagnostics: |
| 208 | + """Compute structured nuisance quality diagnostics for official outputs.""" |
| 209 | + if behavior_predictions is None and nuisance_bundle is not None: |
| 210 | + behavior_predictions = nuisance_bundle.behavior |
| 211 | + outcome_predictions = nuisance_bundle.outcome if nuisance_bundle is not None else None |
| 212 | + |
| 213 | + behavior = _compute_behavior_diagnostics( |
| 214 | + df, |
| 215 | + action_col=action_col, |
| 216 | + behavior_predictions=behavior_predictions, |
| 217 | + propensity_source=propensity_source, |
| 218 | + ) |
| 219 | + outcome = _compute_outcome_diagnostics( |
| 220 | + df, |
| 221 | + target=target, |
| 222 | + feature_cols=feature_cols, |
| 223 | + action_col=action_col, |
| 224 | + estimator=estimator, |
| 225 | + outcome_predictions=outcome_predictions, |
| 226 | + ) |
| 227 | + warnings = tuple(list(behavior.warnings) + list(outcome.warnings)) |
| 228 | + return NuisanceDiagnostics(behavior=behavior, outcome=outcome, warnings=warnings) |
0 commit comments