Spaces:
Sleeping
Sleeping
Download src/explainability.py from frigate-global/financial-risk-api: direct link, hf CLI and curl.
- Browser
- Download file 11.1 kB
-
https://huggingface.co/spaces/frigate-global/financial-risk-api/resolve/main/src/explainability.py
- Command line
-
hf download hf://spaces/frigate-global/financial-risk-api/src/explainability.py
-
curl -L -o explainability.py https://huggingface.co/spaces/frigate-global/financial-risk-api/resolve/main/src/explainability.py
11.1 kB
| 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 | |