"""Permutation importance and SHAP explainability for the best-performing model.""" import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import pandas as pd import shap from sklearn.inspection import permutation_importance def permutation_importance_report(model, X_test, y_test, save_csv, save_plot, n_repeats=20, random_state=42): result = permutation_importance( model, X_test, y_test, n_repeats=n_repeats, random_state=random_state, scoring="average_precision", n_jobs=-1 ) df = pd.DataFrame( { "feature": X_test.columns, "importance_mean": result.importances_mean, "importance_std": result.importances_std, } ).sort_values("importance_mean", ascending=False) save_csv.parent.mkdir(parents=True, exist_ok=True) df.to_csv(save_csv, index=False) top = df.head(20).iloc[::-1] fig, ax = plt.subplots(figsize=(6, 8)) ax.barh(top["feature"], top["importance_mean"], xerr=top["importance_std"]) ax.set_xlabel("Permutation importance (avg. precision drop)") fig.tight_layout() fig.savefig(save_plot, dpi=150) plt.close(fig) return df def shap_summary(model, X_sample, save_plot, max_display=20): explainer = shap.TreeExplainer(model) shap_values = explainer.shap_values(X_sample) fig = plt.figure() shap.summary_plot(shap_values, X_sample, max_display=max_display, show=False) save_plot.parent.mkdir(parents=True, exist_ok=True) fig.savefig(save_plot, dpi=150, bbox_inches="tight") plt.close(fig)