Spaces:
Sleeping
Sleeping
Download src/feature_trust_engine.py from frigate-global/financial-risk-api: direct link, hf CLI and curl.
- Browser
- Download file 5.24 kB
-
https://huggingface.co/spaces/frigate-global/financial-risk-api/resolve/main/src/feature_trust_engine.py
- Command line
-
hf download hf://spaces/frigate-global/financial-risk-api/src/feature_trust_engine.py
-
curl -L -o feature_trust_engine.py https://huggingface.co/spaces/frigate-global/financial-risk-api/resolve/main/src/feature_trust_engine.py
5.24 kB
| import os | |
| import sqlite3 | |
| import pandas as pd | |
| import numpy as np | |
| # Weights for FTS calculation | |
| W_PREDICTIVE = 0.35 | |
| W_STABILITY = 0.25 | |
| W_DRIFT = 0.25 | |
| W_CAUSAL = 0.15 | |
| class FeatureTrustEngine: | |
| """Dynamically audits, decay-tracks, and logs Feature Trust Scores (FTS) in production.""" | |
| def __init__(self, db_path): | |
| self.db_path = db_path | |
| def calculate_fts(self, feature_name, predictive_auc, domain_stability, drift_resistance, causal_stability): | |
| """Calculates FTS composite index (0.0 to 1.0).""" | |
| fts = ( | |
| W_PREDICTIVE * predictive_auc + | |
| W_STABILITY * domain_stability + | |
| W_DRIFT * drift_resistance + | |
| W_CAUSAL * causal_stability | |
| ) | |
| return float(np.clip(fts, 0.0, 1.0)) | |
| def log_feature_trust(self, model_version, feature_name, trust_score, stability, drift, causal): | |
| """Logs calculated FTS to SQL database table.""" | |
| status = "ACTIVE" | |
| if trust_score < 0.40: | |
| status = "SUPPRESSED" | |
| elif trust_score < 0.55: | |
| status = "DECAYED" | |
| conn = sqlite3.connect(self.db_path) | |
| cursor = conn.cursor() | |
| cursor.execute(""" | |
| INSERT INTO feature_trust_logs ( | |
| model_version, feature_name, trust_score, stability_score, drift_score, causal_score, status | |
| ) VALUES (?, ?, ?, ?, ?, ?, ?) | |
| """, (model_version, feature_name, trust_score, stability, drift, causal, status)) | |
| conn.commit() | |
| conn.close() | |
| def load_active_suppressions(self, model_version): | |
| """Loads all feature names that have decayed below the suppression threshold (0.40).""" | |
| conn = sqlite3.connect(self.db_path) | |
| # Select latest log entry for each feature | |
| query = """ | |
| SELECT feature_name, trust_score FROM feature_trust_logs ft1 | |
| WHERE log_id = ( | |
| SELECT MAX(log_id) FROM feature_trust_logs ft2 | |
| WHERE ft2.feature_name = ft1.feature_name AND ft2.model_version = ? | |
| ) AND status = 'SUPPRESSED' | |
| """ | |
| df = pd.read_sql_query(query, conn, params=(model_version,)) | |
| conn.close() | |
| if df.empty: | |
| return {} | |
| return dict(zip(df["feature_name"], df["trust_score"])) | |
| def suppress_untrusted_features(self, df_features, model_version="xgb_v1.0"): | |
| """Suppresses untrusted features (replacing values with the median of active domain) | |
| to prevent decayed signals from corrupting XGBoost predictions. | |
| """ | |
| df_out = df_features.copy() | |
| suppressions = self.load_active_suppressions(model_version) | |
| if not suppressions: | |
| return df_out | |
| print(f"Feature Trust Engine suppressing decayed features: {list(suppressions.keys())}") | |
| for feat in suppressions: | |
| if feat in df_out.columns: | |
| # Replace with median or default constant | |
| median_val = float(df_out[feat].median()) if len(df_out) > 0 else 0.0 | |
| df_out[feat] = median_val | |
| return df_out | |
| def evaluate_and_log_all_features(self, model_version, df_test, feature_importances, feature_names): | |
| """Runs the complete FTS evaluation on all features and commits logs to the database.""" | |
| # Simple placeholder metrics calculation per feature | |
| # In production, these are evaluated using SHAP, transfer AUC, and PSI checks. | |
| import random | |
| random.seed(42) | |
| records = [] | |
| for feat in feature_names: | |
| importance = feature_importances.get(feat, 0.02) | |
| # Higher importance translates to higher base predictive contribution | |
| pred_auc = min(0.99, 0.50 + importance * 3.0) | |
| # Simulated drift and stability | |
| stability = random.uniform(0.70, 0.95) | |
| drift = random.uniform(0.75, 0.98) | |
| causal = random.uniform(0.65, 0.92) | |
| # Simulate artificial decay for a specific feature (e.g. subscription_growth_rate or age) to show suppression pathway | |
| if feat in ["subscription_growth_rate", "emergency_borrowing_30d"]: | |
| pred_auc *= 0.40 | |
| stability *= 0.40 | |
| drift *= 0.30 | |
| fts = self.calculate_fts(feat, pred_auc, stability, drift, causal) | |
| status = "ACTIVE" | |
| if fts < 0.40: | |
| status = "SUPPRESSED" | |
| elif fts < 0.55: | |
| status = "DECAYED" | |
| records.append((model_version, feat, fts, stability, drift, causal, status)) | |
| conn = sqlite3.connect(self.db_path) | |
| cursor = conn.cursor() | |
| cursor.executemany(""" | |
| INSERT INTO feature_trust_logs ( | |
| model_version, feature_name, trust_score, stability_score, drift_score, causal_score, status | |
| ) VALUES (?, ?, ?, ?, ?, ?, ?) | |
| """, records) | |
| conn.commit() | |
| conn.close() | |
| print(f"Logged FTS values for {len(feature_names)} features under model version {model_version}.") | |