File size: 5,237 Bytes
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75fce80
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75fce80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc308f6
 
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
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}.")