File size: 1,318 Bytes
d82ffcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import shap
import lime
import lime.lime_tabular
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

class ModelExplainer:
    """SHAP and LIME explanations for the ensemble model."""
    
    def __init__(self, model, feature_names: list):
        self.model = model
        self.feature_names = feature_names
        
    def shap_explain(self, X_background, X_explain):
        """Generate SHAP values."""
        explainer = shap.TreeExplainer(self.model.xgb_model)  # Use XGB as proxy
        shap_values = explainer.shap_values(X_explain)
        return shap_values, explainer.expected_value
        
    def plot_shap_summary(self, shap_values, X):
        shap.summary_plot(shap_values, X, feature_names=self.feature_names, show=False)
        plt.tight_layout()
        return plt.gcf()
        
    def lime_explain_instance(self, X_train, instance, num_features=10):
        """Explain a single prediction with LIME."""
        explainer = lime.lime_tabular.LimeTabularExplainer(
            X_train,
            feature_names=self.feature_names,
            class_names=['Down', 'Up'],
            mode='classification'
        )
        exp = explainer.explain_instance(instance, self.model.predict_proba, num_features=num_features)
        return exp