Spaces:
Build error
Build error
Download src/analysis/explainer.py from leovean/Forex-AI-Analyst: direct link, hf CLI and curl.
- Browser
- Download file 1.32 kB
-
https://huggingface.co/spaces/leovean/Forex-AI-Analyst/resolve/main/src/analysis/explainer.py
- Command line
-
hf download hf://spaces/leovean/Forex-AI-Analyst/src/analysis/explainer.py
-
curl -L -o explainer.py https://huggingface.co/spaces/leovean/Forex-AI-Analyst/resolve/main/src/analysis/explainer.py
1.32 kB
| 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 |