File size: 11,109 Bytes
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import numpy as np
import shap
import json

class RiskExplainer:
    """Uses SHAP TreeExplainer to calculate feature contributions for ML models
    and translates them into human-readable explanations.
    """
    
    def __init__(self, xgb_model, feature_names):
        """Initializes the SHAP TreeExplainer.
        
        Args:
            xgb_model: The trained XGBoost model (non-calibrated classifier wrapper)
            feature_names (list): List of feature names in order of model input
        """
        self.xgb_model = xgb_model
        self.feature_names = feature_names
        try:
            # TreeExplainer for tree-based models doesn't strictly require background data
            # for path-dependent feature attribution, which is fast and reliable.
            self.explainer = shap.TreeExplainer(self.xgb_model)
            print("SHAP TreeExplainer initialized successfully.")
        except Exception as e:
            print(f"Error initializing SHAP TreeExplainer: {e}. Fallback explainability will be used.")
            self.explainer = None
            
    def explain_prediction(self, X_input, features_dict):
        """Computes SHAP values and returns sorted positive/negative human-readable explanations.
        
        Args:
            X_input (np.ndarray): 2D numpy array containing the preprocessed features for the user (1 x N)
            features_dict (dict): Dictionary containing the raw user features for explanation formatting
            
        Returns:
            dict: {
                "shap_values": {feature: shap_val},
                "top_risk_factors": list,
                "top_positive_factors": list
            }
        """
        shap_vals = None
        
        # 1. Attempt SHAP calculation
        if self.explainer is not None:
            try:
                # Shape: (1, num_features)
                shap_output = self.explainer.shap_values(X_input)
                # XGBoost binary classification returns a 1D array of SHAP values for class 1
                if isinstance(shap_output, list):
                    # In some shap versions, binary classification returns [neg_shap, pos_shap]
                    shap_vals = shap_output[1][0]
                elif len(shap_output.shape) == 3:
                    shap_vals = shap_output[0, :, 1]
                elif len(shap_output.shape) == 2:
                    shap_vals = shap_output[0]
                else:
                    shap_vals = shap_output
            except Exception as e:
                print(f"SHAP explanation calculation failed: {e}. Falling back to heuristic explanation.")
                shap_vals = None
                
        # 2. Fallback heuristic explanation if SHAP fails
        if shap_vals is None:
            shap_vals = self._compute_fallback_importance(X_input)
            
        # Map feature names to SHAP values
        shap_map = {name: float(val) for name, val in zip(self.feature_names, shap_vals)}
        
        # Sort features by contribution
        # Positive values -> increase risk (Risk Factors)
        # Negative values -> decrease risk (Positive/Mitigating Factors)
        risk_sorted = sorted(
            [(name, val) for name, val in shap_map.items() if val > 0.001],
            key=lambda x: x[1],
            reverse=True
        )
        
        positive_sorted = sorted(
            [(name, val) for name, val in shap_map.items() if val < -0.001],
            key=lambda x: x[1]
        )
        
        # Generate human-readable explanations
        top_risk_factors = []
        for name, val in risk_sorted[:3]:
            explanation = self._translate_to_readable(name, features_dict, is_risk=True)
            if explanation:
                top_risk_factors.append(explanation)
                
        top_positive_factors = []
        for name, val in positive_sorted[:3]:
            explanation = self._translate_to_readable(name, features_dict, is_risk=False)
            if explanation:
                top_positive_factors.append(explanation)
                
        # Handle empty lists with general fallbacks
        if not top_risk_factors:
            top_risk_factors.append("Low overall transactional risk indicators.")
        if not top_positive_factors:
            top_positive_factors.append("Profile metrics align with standard baseline population.")
            
        return {
            "shap_values": shap_map,
            "top_risk_factors": top_risk_factors,
            "top_positive_factors": top_positive_factors
        }
        
    def _compute_fallback_importance(self, X_input):
        """Fast fallback helper that approximates feature contribution using feature importances."""
        try:
            importances = self.xgb_model.feature_importances_
        except:
            importances = np.ones(len(self.feature_names)) / len(self.feature_names)
            
        # Simple heuristic: sign is positive if feature value is higher than standard averages
        # (For features where higher value means higher risk, like volatility, debt ratio)
        # Let's create dummy shap values
        dummy_shap = np.zeros(len(self.feature_names))
        for i, name in enumerate(self.feature_names):
            val = X_input[0, i]
            # If missing or NaN, set to low risk contribution
            if np.isnan(val):
                dummy_shap[i] = 0.0
                continue
                
            # Heuristic direction
            if name in ["debt_to_income_ratio", "income_volatility", "expense_volatility", 
                        "liquidity_decay_rate", "behavioural_risk_score", "subscription_growth_rate", 
                        "spending_trend_velocity", "recent_failed_payments_30d", "overdraft_days_30d", 
                        "emergency_borrowing_30d"]:
                # High values increase risk
                dummy_shap[i] = importances[i] * (val - 0.2) # Simple mean shift centered around 0.2
            else:
                # High values decrease risk (credit_score, runway_months, savings_rate, total_balance)
                dummy_shap[i] = -importances[i] * (val - 0.5)
                
        return dummy_shap

    def _translate_to_readable(self, feature_name, val_dict, is_risk):
        """Translates a feature and its value into a dynamic, human-readable statement."""
        val = val_dict.get(feature_name)
        
        # 1. Missingness flags
        if feature_name.startswith("has_") and val == 0:
            if feature_name == "has_transaction_history":
                return "No transactional history available (thin file profile)."
            if feature_name == "has_credit_score":
                return "No traditional credit score available from bureau."
            if feature_name == "has_questionnaire_data":
                return "Questionnaire profile data is missing."
            return f"Missing key data feed: {feature_name.replace('has_', '')}."

        is_nan = False
        if isinstance(val, (int, float, np.number)):
            is_nan = np.isnan(val)
        if val is None or is_nan:
            return None
            
        # 2. Runway Months
        if feature_name == "runway_months":
            if is_risk:
                return f"Thin savings runway: only {val:.1f} months of expenses covered."
            else:
                return f"Solid cash runway: {val:.1f} months of expenses covered."
                
        # 3. Debt to Income Ratio
        if feature_name == "debt_to_income_ratio":
            if is_risk:
                return f"Elevated debt-to-income ratio of {val*100:.1f}%."
            else:
                return f"Low debt-to-income ratio of {val*100:.1f}%."
                
        # 4. Savings Rate
        if feature_name == "savings_rate":
            if is_risk:
                return f"Negative cashflow: spending exceeds income by {abs(val)*100:.1f}%."
            else:
                return f"Healthy savings rate: saving {val*100:.1f}% of monthly income."
                
        # 5. Volatilities
        if feature_name == "income_volatility":
            if is_risk:
                return f"High income volatility: paycheck variance is {val*100:.1f}%."
            else:
                return "Stable paycheck deposit amount."
                
        if feature_name == "expense_volatility":
            if is_risk:
                return f"Highly volatile monthly expenses (variance: {val*100:.1f}%)."
            else:
                return "Predictable, low-variance monthly spending pattern."
                
        # 6. Liquidity Decay Rate
        if feature_name == "liquidity_decay_rate":
            if is_risk:
                return f"Account liquidity is decaying at {val*100:.1f}% per day."
            else:
                return f"Account balance is growing or stable (decay rate: {val*100:.1f}%)."
                
        # 7. Spending Trend Velocity
        if feature_name == "spending_trend_velocity":
            if is_risk:
                return f"Discretionary spending has accelerated by {(val-1.0)*100:.1f}% over the last 30 days."
            else:
                return f"Discretionary spending has contracted by {abs(val-1.0)*100:.1f}% (positive spending control)."
                
        # 8. Subscription Growth
        if feature_name == "subscription_growth_rate":
            if is_risk:
                return f"Rapid growth in subscription spend: up {val*100:.1f}% in the last 30 days."
            else:
                return "Subscription spending is flat or decreasing."
                
        # 9. Behavioral Risk
        if feature_name == "behavioural_risk_score":
            if is_risk:
                return f"High behavioral risk score ({val:.0f}/100) reflecting payment flags or questionnaire traits."
            else:
                return "Good account discipline and self-reported savings habits."
                
        # 10. Direct Risk Indicators
        if feature_name == "recent_failed_payments_30d" and val > 0:
            return f"Failed payments detected: {val} failed billing attempts in the last 30 days."
            
        if feature_name == "overdraft_days_30d" and val > 0:
            return f"Frequent overdraft usage: account spent {val} days in negative balance."
            
        if feature_name == "emergency_borrowing_30d" and val > 0:
            return f"Payday cash advances of ${val:,.2f} drawn in the last 30 days."
            
        # 11. Credit Score
        if feature_name == "credit_score":
            if is_risk:
                return f"Subprime bureau credit score ({val:.0f})."
            else:
                return f"Strong credit bureau score ({val:.0f})."
                
        # 12. Total Balance
        if feature_name == "total_balance":
            if is_risk:
                return f"Low absolute cash reserves: total liquid balance is ${val:,.2f}."
            else:
                return f"Excellent cash reserves: total liquid balance is ${val:,.2f}."

        return None