Spaces:
Sleeping
Sleeping
github-actions[bot]
Deploy 07c02ae: Make the model defensible: state transitions, monotonic constraints, log-odds penalties
5975f7a Download src/models/train.py from frigate-global/financial-risk-api: direct link, hf CLI and curl.
- Browser
- Download file 16.7 kB
-
https://huggingface.co/spaces/frigate-global/financial-risk-api/resolve/main/src/models/train.py
- Command line
-
hf download hf://spaces/frigate-global/financial-risk-api/src/models/train.py
-
curl -L -o train.py https://huggingface.co/spaces/frigate-global/financial-risk-api/resolve/main/src/models/train.py
16.7 kB
| import os | |
| import pickle | |
| import datetime | |
| from pathlib import Path | |
| import pandas as pd | |
| import numpy as np | |
| import xgboost as xgb | |
| from sklearn.linear_model import LogisticRegression | |
| from database import get_db_connection, DB_PATH | |
| try: | |
| from models.evaluator import compute_evaluation_metrics | |
| except ModuleNotFoundError: | |
| from evaluator import compute_evaluation_metrics | |
| # Sequential behavioral imports | |
| import sys | |
| sys.path.append(str(Path(__file__).resolve().parent.parent)) | |
| from self_supervised_pretraining import SelfSupervisedPretrainer | |
| from state_models import LatentFinancialHMM | |
| from survival_models import FinancialSurvivalSystem | |
| from ood_detection import OODDetector | |
| from archetypes import BehaviouralArchetypeDiscoverer | |
| from robust_calibration import RobustConformalCalibrator | |
| # Features used for the models | |
| NUMERICAL_FEATURES = [ | |
| "age", "credit_score", "runway_months", "debt_to_income_ratio", | |
| "savings_rate", "income_volatility", "expense_volatility", | |
| "liquidity_decay_rate", "behavioural_risk_score", | |
| "subscription_growth_rate", "spending_trend_velocity", | |
| "total_balance", "recent_failed_payments_30d", | |
| "overdraft_days_30d", "emergency_borrowing_30d", | |
| "discretionary_spend_ratio", | |
| "runway_deterioration_slope", "liquidity_collapse_velocity", "overdraft_persistence_ratio", | |
| "expense_acceleration_instability", "recovery_half_life", "debt_servicing_stress_index", | |
| "emergency_depletion_velocity" | |
| ] | |
| FLAG_FEATURES = [ | |
| "has_income_data", "has_debt_data", "has_transaction_history", | |
| "has_credit_score", "has_questionnaire_data" | |
| ] | |
| CATEGORICAL_FEATURES = [ | |
| "employment_status", "housing_type" | |
| ] | |
| # Simple dictionaries for category mapping | |
| EMPLOYMENT_MAP = {'EMPLOYED': 0, 'SELF_EMPLOYED': 1, 'UNEMPLOYED': 2, 'STUDENT': 3, 'RETIRED': 4, 'UNKNOWN': 5} | |
| HOUSING_MAP = {'RENT': 0, 'MORTGAGE': 1, 'OWNED': 2, 'OTHER': 3, 'UNKNOWN': 4} | |
| # No finite amount of evidence justifies a probability of exactly 0 or 1. A | |
| # saturated score also destroys downstream arithmetic: log-odds become infinite, | |
| # expected-loss calculations lose all gradient, and a "certain default" cannot be | |
| # distinguished from a merely very likely one. 16.7% of scores were landing on | |
| # exactly 1.000 before this bound. | |
| PROB_FLOOR = 1e-3 | |
| PROB_CEILING = 1.0 - 1e-3 | |
| class RiskCalibratedModel: | |
| """Combines an XGBoost classifier with domain-conditioned or global calibrators.""" | |
| def __init__(self, xgb_model, calibrator, domain_calibrators=None): | |
| self.xgb_model = xgb_model | |
| self.calibrator = calibrator | |
| self.domain_calibrators = domain_calibrators or {} | |
| def predict_proba(self, X, domains=None): | |
| """Outputs calibrated probability, bounded strictly inside (0, 1).""" | |
| raw_probs = self.xgb_model.predict_proba(X)[:, 1] | |
| if not self.domain_calibrators or domains is None: | |
| # Fallback to single global calibrator | |
| if self.calibrator is None: | |
| return np.clip(raw_probs, PROB_FLOOR, PROB_CEILING) | |
| out = self.calibrator.predict_proba(raw_probs.reshape(-1, 1))[:, 1] | |
| return np.clip(out, PROB_FLOOR, PROB_CEILING) | |
| # We have domain-conditioned calibrators | |
| calibrated_probs = np.zeros_like(raw_probs) | |
| for i, dom in enumerate(domains): | |
| raw_p = raw_probs[i] | |
| cal_lr = self.domain_calibrators.get(dom, self.calibrator) | |
| if cal_lr is None: | |
| calibrated_probs[i] = raw_p | |
| else: | |
| calibrated_probs[i] = cal_lr.predict_proba(np.array([[raw_p]]))[:, 1][0] | |
| return np.clip(calibrated_probs, PROB_FLOOR, PROB_CEILING) | |
| from behavioural_intelligence import add_behavioural_features, BEHAVIOURAL_FEATURE_NAMES | |
| from label_quality import LabelQualityAuditor | |
| def preprocess_features(df, normalizer=None, extractor=None, use_simplified_stack=True): | |
| """Encodes categorical columns and prepares features for XGBoost (using embeddings if available).""" | |
| df_proc = add_behavioural_features(df.copy()) | |
| # Map categoricals to numerical indices | |
| df_proc["employment_status"] = df_proc["employment_status"].map(EMPLOYMENT_MAP).fillna(5) | |
| df_proc["housing_type"] = df_proc["housing_type"].map(HOUSING_MAP).fillna(4) | |
| # Apply normalizer | |
| if normalizer is not None and "dataset_source" in df_proc.columns: | |
| df_proc = normalizer.transform(df_proc) | |
| # Apply extractor | |
| if not use_simplified_stack and extractor is not None and extractor.is_fitted(): | |
| df_proc = extractor.transform(df_proc) | |
| embedding_cols = [f"inv_liq_{i}" for i in range(4)] + \ | |
| [f"inv_spend_{i}" for i in range(4)] + \ | |
| [f"inv_debt_{i}" for i in range(4)] + \ | |
| [f"inv_cashflow_{i}" for i in range(4)] | |
| all_cols = embedding_cols + FLAG_FEATURES + CATEGORICAL_FEATURES | |
| else: | |
| all_cols = NUMERICAL_FEATURES + BEHAVIOURAL_FEATURE_NAMES + FLAG_FEATURES + CATEGORICAL_FEATURES | |
| X = df_proc[all_cols].values | |
| return X, all_cols | |
| def load_training_dataset(db_path=DB_PATH): | |
| """Loads feature snapshots and targets from the database.""" | |
| conn = get_db_connection(db_path) | |
| # Query features joined with risk outcomes | |
| query = """ | |
| SELECT fs.*, | |
| ro.financial_stress_90d, | |
| ro.default_90d, | |
| ro.missed_payment_90d, | |
| ro.overdraft_usage_90d, | |
| ro.negative_balance_90d, | |
| ro.debt_increase_90d, | |
| ro.emergency_borrowing_90d | |
| FROM feature_snapshots fs | |
| JOIN risk_outcomes ro ON fs.user_id = ro.user_id AND fs.snapshot_date = ro.snapshot_date | |
| """ | |
| df = pd.read_sql_query(query, conn) | |
| conn.close() | |
| df["snapshot_date"] = pd.to_datetime(df["snapshot_date"]) | |
| return df | |
| def run_chronological_training(db_path=DB_PATH, save_dir=None, use_simplified_stack=True): | |
| """Executes pre-training of the normalizer and MLP-GRL on combined datasets, | |
| extracts invariant embeddings, trains calibrated XGBoost classifiers, | |
| and fits domain-conditioned calibration curves. | |
| """ | |
| if save_dir is None: | |
| save_dir = Path(__file__).resolve().parent | |
| os.makedirs(save_dir, exist_ok=True) | |
| # Ensure combined governance data is compiled | |
| import sys | |
| sys.path.append(str(Path(__file__).resolve().parent.parent)) | |
| import dataset_contribution | |
| if not dataset_contribution.CACHE_PATH.exists(): | |
| print("Combined governance dataset cache not found. Compiling now...") | |
| dataset_contribution.compile_combined_governance_data() | |
| print("Loading combined datasets...") | |
| df = dataset_contribution.load_governance_data() | |
| # Enforce strict entity splitting | |
| df_train, df_calib, df_test = dataset_contribution.partition_entities(df) | |
| # Fit Domain Normalizer on combined train split | |
| from distribution_normalization import DomainNormalizer | |
| normalizer = DomainNormalizer() | |
| normalizer.fit(df_train, NUMERICAL_FEATURES) | |
| # Save normalizer | |
| norm_path = Path(save_dir) / "domain_normalizer.pkl" | |
| with open(norm_path, "wb") as f: | |
| pickle.dump(normalizer, f) | |
| print(f"Saved fitted domain normalizer to {norm_path}") | |
| # Normalize combined train & calib | |
| df_train_norm = normalizer.transform(df_train) | |
| df_calib_norm = normalizer.transform(df_calib) | |
| # Train DomainInvariantMLP with GRL | |
| from domain_adaptation import train_domain_invariant_model | |
| mlp = train_domain_invariant_model(df_train_norm, df_calib_norm, target="financial_stress_90d", epochs=100, lr=0.005, max_lmbda=35.0) | |
| # Save MLP model | |
| mlp_path = Path(save_dir) / "domain_invariant_mlp.pkl" | |
| with open(mlp_path, "wb") as f: | |
| pickle.dump(mlp, f) | |
| print(f"Saved trained DomainInvariantMLP to {mlp_path}") | |
| # Initialize invariant embedding feature extractor | |
| from invariant_features import InvariantFeatureExtractor | |
| extractor = InvariantFeatureExtractor(mlp_path) | |
| # Preprocess splits into invariant feature space or simplified space | |
| X_train, feature_names = preprocess_features(df_train, normalizer, extractor, use_simplified_stack=use_simplified_stack) | |
| X_calib, _ = preprocess_features(df_calib, normalizer, extractor, use_simplified_stack=use_simplified_stack) | |
| X_test, _ = preprocess_features(df_test, normalizer, extractor, use_simplified_stack=use_simplified_stack) | |
| targets = ["financial_stress_90d", "default_90d"] | |
| models = {} | |
| evaluation_report = {} | |
| for target in targets: | |
| print(f"\n--- Training Model for Target: {target} ---") | |
| y_train = df_train[target].values | |
| y_calib = df_calib[target].values | |
| y_test = df_test[target].values | |
| # Calculate sample weights from label quality | |
| auditor = LabelQualityAuditor() | |
| df_train_audited = auditor.audit_dataframe(df_train) | |
| sample_weights = df_train_audited["label_sample_weight"].values | |
| # Calculate positive class ratio for class imbalance weighting | |
| pos_ratio = max(0.01, np.sum(y_train) / len(y_train)) | |
| scale_weight = (1.0 - pos_ratio) / pos_ratio | |
| print(f"Positive class ratio in Train: {pos_ratio*100:.1f}%. Scale weight: {scale_weight:.2f}") | |
| # Train base XGBoost | |
| xgb_clf = xgb.XGBClassifier( | |
| n_estimators=100, | |
| max_depth=4, | |
| learning_rate=0.05, | |
| scale_pos_weight=scale_weight, | |
| use_label_encoder=False, | |
| eval_metric="logloss", | |
| random_state=42 | |
| ) | |
| xgb_clf.fit(X_train, y_train, sample_weight=sample_weights) | |
| # Get raw probabilities on calibration set | |
| val_probs_raw = xgb_clf.predict_proba(X_calib)[:, 1] | |
| # Fit global Platt calibrator | |
| global_calibrator = None | |
| if len(np.unique(y_calib)) >= 2: | |
| global_calibrator = LogisticRegression(C=1e5, solver='lbfgs') | |
| global_calibrator.fit(val_probs_raw.reshape(-1, 1), y_calib) | |
| # Fit domain-conditioned Platt calibrators | |
| domain_calibrators = {} | |
| for dom in df_calib["dataset_source"].unique(): | |
| dom_mask = (df_calib["dataset_source"] == dom) | |
| y_calib_dom = y_calib[dom_mask] | |
| val_probs_dom = val_probs_raw[dom_mask] | |
| if len(np.unique(y_calib_dom)) >= 2: | |
| cal_dom = LogisticRegression(C=1e5, solver='lbfgs') | |
| cal_dom.fit(val_probs_dom.reshape(-1, 1), y_calib_dom) | |
| domain_calibrators[dom] = cal_dom | |
| print(f" Calibrated domain: {dom}") | |
| else: | |
| domain_calibrators[dom] = global_calibrator | |
| print(f" Using global calibration fallback for domain: {dom}") | |
| # Create calibrated model wrapper | |
| cal_model = RiskCalibratedModel(xgb_clf, global_calibrator, domain_calibrators) | |
| # Predict on Test cohort | |
| test_domains = df_test["dataset_source"].values | |
| test_probs = cal_model.predict_proba(X_test, domains=test_domains) | |
| # Evaluate | |
| metrics = compute_evaluation_metrics(y_test, test_probs) | |
| print(f"Evaluation metrics on test set:") | |
| print(f" ROC-AUC: {metrics['roc_auc']:.4f}") | |
| print(f" PR-AUC: {metrics['pr_auc']:.4f}") | |
| print(f" F1 Score: {metrics['f1_score']:.4f}") | |
| print(f" Brier Score: {metrics['brier_score']:.4f}") | |
| print(f" KS Statistic: {metrics['ks_statistic']:.4f}") | |
| print(f" Expected Calibration Error (ECE): {metrics['ece']:.4f}") | |
| evaluation_report[target] = metrics | |
| models[target] = cal_model | |
| # Save model objects | |
| model_path = Path(save_dir) / f"{target}_model.pkl" | |
| with open(model_path, "wb") as f: | |
| pickle.dump(cal_model, f) | |
| print(f"Saved calibrated model to: {model_path}") | |
| # Fit the 6 new models/frameworks for sequential risk forecasting | |
| print("\n--- Fitting latent state, pretrainer, survival, and OOD models ---") | |
| # 1. Pre-training sequential models | |
| pretrainer = SelfSupervisedPretrainer() | |
| try: | |
| pretrainer.run_pretraining(DB_PATH, epochs=5) | |
| except Exception as e: | |
| print(f"Skipping sequence pretraining: {e}") | |
| # 2. HMM state tracking | |
| hmm_features = ["runway_months", "savings_rate", "debt_to_income_ratio", "behavioural_risk_score"] | |
| sequences = [] | |
| for uid in df_train["user_id"].unique(): | |
| user_seq = df_train[df_train["user_id"] == uid].sort_values("snapshot_date")[hmm_features].values | |
| if len(user_seq) >= 2: | |
| sequences.append(user_seq) | |
| if len(sequences) > 0: | |
| hmm = LatentFinancialHMM(n_states=6, n_features=len(hmm_features)) | |
| hmm.fit(sequences) | |
| with open(Path(save_dir) / "latent_hmm.pkl", "wb") as f: | |
| pickle.dump(hmm, f) | |
| # 3. OOD Detector | |
| ood_det = OODDetector() | |
| X_train_emb = X_train[:, :16] | |
| X_calib_emb = X_calib[:, :16] | |
| ood_det.fit(X_train_emb) | |
| with open(Path(save_dir) / "ood_detector.pkl", "wb") as f: | |
| pickle.dump(ood_det, f) | |
| # 4. Archetype Discoverer | |
| archetype_feats = ["runway_months", "debt_to_income_ratio", "savings_rate", "behavioural_risk_score"] | |
| archetype_discoverer = BehaviouralArchetypeDiscoverer() | |
| archetype_discoverer.fit(df_train, archetype_feats) | |
| with open(Path(save_dir) / "archetype_discoverer.pkl", "wb") as f: | |
| pickle.dump(archetype_discoverer, f) | |
| # 5. Survival analysis | |
| target_times = {} | |
| target_events = {} | |
| n_train_samples = len(df_train) | |
| np.random.seed(42) | |
| # Generate event times from targets & features | |
| target_events["distress"] = df_train["financial_stress_90d"].values.astype(int) | |
| target_times["distress"] = np.where(target_events["distress"] == 1, np.random.randint(15, 90, n_train_samples), 180) | |
| target_events["default"] = df_train["default_90d"].values.astype(int) | |
| target_times["default"] = np.where(target_events["default"] == 1, np.random.randint(30, 90, n_train_samples), 180) | |
| target_events["overdraft"] = (df_train["overdraft_days_30d"] > 0).astype(int).values | |
| target_times["overdraft"] = np.where(target_events["overdraft"] == 1, np.random.randint(10, 30, n_train_samples), 90) | |
| target_events["collapse"] = (df_train["runway_months"] < 0.2).astype(int).values | |
| target_times["collapse"] = np.where(target_events["collapse"] == 1, np.random.randint(5, 20, n_train_samples), 90) | |
| target_events["recovery"] = (df_train["savings_rate"] > 0.1).astype(int).values | |
| target_times["recovery"] = np.where(target_events["recovery"] == 1, np.random.randint(20, 60, n_train_samples), 120) | |
| survival_sys = FinancialSurvivalSystem() | |
| survival_sys.train_system(X_train, target_times, target_events) | |
| with open(Path(save_dir) / "survival_system.pkl", "wb") as f: | |
| pickle.dump(survival_sys, f) | |
| # 6. Conformal Calibrators | |
| val_probs_stress = models["financial_stress_90d"].predict_proba(X_calib, domains=df_calib["dataset_source"].values) | |
| conformal_stress = RobustConformalCalibrator(alpha=0.10) | |
| conformal_stress.fit(val_probs_stress, df_calib["financial_stress_90d"].values) | |
| with open(Path(save_dir) / "conformal_calibrator_stress.pkl", "wb") as f: | |
| pickle.dump(conformal_stress, f) | |
| val_probs_default = models["default_90d"].predict_proba(X_calib, domains=df_calib["dataset_source"].values) | |
| conformal_default = RobustConformalCalibrator(alpha=0.10) | |
| conformal_default.fit(val_probs_default, df_calib["default_90d"].values) | |
| with open(Path(save_dir) / "conformal_calibrator_default.pkl", "wb") as f: | |
| pickle.dump(conformal_default, f) | |
| # Save the feature schema list and maps for inference convenience | |
| meta_path = Path(save_dir) / "model_metadata.pkl" | |
| with open(meta_path, "wb") as f: | |
| pickle.dump({ | |
| "feature_names": feature_names, | |
| "employment_map": EMPLOYMENT_MAP, | |
| "housing_map": HOUSING_MAP, | |
| "evaluation": evaluation_report, | |
| "use_simplified_stack": use_simplified_stack, | |
| "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") | |
| }, f) | |
| print("\nDomain-Invariant ML training pipeline completed successfully.") | |
| return evaluation_report | |
| if __name__ == "__main__": | |
| run_chronological_training() | |