ds-utils-xai
Explainable AI (XAI) and model interpretation for tree-based models. Use for plotting feature importance rankings, rendering Graphviz decision tree diagrams…
от idanmoradarthas★ 37 звёзд на GitHub
Установить ds-utils-xai в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
ds-utils-xai
Explainable AI visualizers and interpretation methods for tree-based scikit-learn models.
Purpose
ds_utils.xai provides tools to inspect and communicate tree-based model decisions. It provides feature importance ranking bar charts and Graphviz DOT rendering into matplotlib axes. Alongside them, scikit-learn's plot_tree draws a tree with matplotlib only and export_text returns its rules as text.
- When to use: Explaining tree ensembles (Random Forest, Gradient Boosting, LightGBM, XGBoost) and visualizing single decision tree decision rules.
- When NOT to use: For linear model coefficient analysis (coef_), SHAP/LIME game-theoretic values, neural networks, or unsupervised clustering.
Prerequisites
- Python 3.11 or higher.
- data-science-utils package installed (pip install data-science-utils).
- Core dependencies: numpy, scikit-learn, matplotlib, pydotplus.
- System Graphviz installation (apt-get install graphviz or brew install graphviz) for draw_dot_data (plot_tree and export_text do not need it).
Instructions
Task-to-Approach Map
| Interpretation Goal | Function | Target Model | Output Type |
|---|---|---|---|
| Rank features by global impact | plot_features_importance |
Any tree model with .feature_importances_ |
Matplotlib Axes |
| Visualize decision tree structure | draw_dot_data / plot_tree (scikit-learn) |
Single DecisionTreeClassifier or DecisionTreeRegressor |
Matplotlib Axes |
| Export tree rules as text | export_text (scikit-learn) |
Single DecisionTreeClassifier or DecisionTreeRegressor |
Text string |
Exhaustive signatures, parameters, and return details are in references/api_reference.md.
End-to-End Tree Model Interpretation Workflow
Fitted Model Available
│
┌──────────────────┴──────────────────┐
▼ ▼
Tree Ensemble Single Decision Tree
(Random Forest / GBDT) │
│ │
├──────────────────────────┐ │
▼ ▼ │
Global Importance Surrogate Tree │
(plot_features_importance) (explain forest)│
│ │
┌──────────────────────────┴──────────┴─────────────┐
▼ ▼
Visual Tree Graph Text Rule Export
(draw_dot_data / plot_tree) (export_text)
Inputs you need
The steps below assume:
- Your fitted tree model: an ensemble (e.g.
rf = RandomForestClassifier().fit(X_train, y_train)) and/or a single decision tree estimatordt. - Your training feature matrix
X_train, held-out test splitsX_test,y_test. - Feature column names list:
feature_names = list(X_train.columns). - Class label names from your model:
class_names = [str(c) for c in rf.classes_].
import pandas as pd
# Load your dataset (replace with your data)
df = pd.read_csv("your_dataset")
# X_train, X_test, y_train, y_test = train_test_split(...)
# rf = RandomForestClassifier(random_state=42).fit(X_train, y_train)
Step 1: Global Feature Importance (plot_features_importance)
Question: which features have the strongest global contribution in the tree ensemble, and does held-out permutation cross-check corroborate the ranking?
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.inspection import permutation_importance
from ds_utils.xai import plot_features_importance
# 1. Impurity-based feature importance from your fitted forest
feature_names = list(X_train.columns) if hasattr(X_train, "columns") else [f"feat_{i}" for i in range(X_train.shape[1])]
ax_imp = plot_features_importance(feature_names, rf.feature_importances_)
plt.close()
# 2. Held-out cross-check via permutation importance on test split
perm_res = permutation_importance(rf, X_test, y_test, n_repeats=10, random_state=42)
perm_series = pd.Series(perm_res.importances_mean, index=feature_names).sort_values(ascending=False)
print("Top permutation importances on test split:\n", perm_series.head(5))
- What to look for: Discrepancies between impurity importance and permutation importance on held-out test data.
- Action: Verify that top features are valid business signals and not leaked artifacts.
- Caution: Impurity importance is computed on training data and favors continuous or high-cardinality features; always cross-check with permutation importance on held-out data.
Step 2: Surrogate Shallow Tree & Fidelity Check
Question: does a shallow decision tree accurately approximate the predictions of the complex ensemble on held-out data?
from sklearn.tree import DecisionTreeClassifier
# Fit a shallow surrogate tree on the forest's predictions
dt = DecisionTreeClassif
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
- references/api_reference.md
FAQ
Что делает скилл ds-utils-xai?
Explainable AI (XAI) and model interpretation for tree-based models. Use for plotting feature importance rankings, rendering Graphviz decision tree diagrams, and exporting decision rules as text. Do NOT use for linear models, neural network interpretability, or clustering.
Как установить скилл ds-utils-xai?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл ds-utils-xai запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
AnthropicToolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
access
AnthropicManage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
configure
AnthropicSet up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
access
AnthropicManage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…