Imported from idanmoradarthas/DataScienceUtils (
skills/xai/SKILL.md). Install upstream withnpx skills add idanmoradarthas/DataScienceUtils --skill xai. Copyright stays with the author (MIT).
XAI — ds_utils.xai
Explainable AI visualizers and interpretation methods.
Installation
pip install data-science-utils
# or
conda install -c idanmorad data-science-utils
Import
from ds_utils.xai import plot_features_importance
from ds_utils.xai import draw_dot_data
plot_features_importance
Plots a feature importance bar chart, ranking features by their calculated impact on the model's decisions.
from ds_utils.xai import plot_features_importance
import matplotlib.pyplot as plt
# complete usage example
plot_features_importance(features_names, clf.feature_importances_)
plt.show()
Parameters:
feature_names— list, Names of the features used during training.feature_importances— array-like, Model's feature importances.
Returns: matplotlib Axes.
Common mistakes:
- The
feature_namesorder MUST match the column order used in.fit(). - This function only works with tree-based models that expose
.feature_importances_(e.g., Decision Tree, Random Forest, GradientBoosting, XGBoost). - Does NOT work with linear models since
.coef_implies a different interpretation scale and meaning.
draw_dot_data
Renders a decision tree image from a Graphviz DOT string (for example, DOT produced by sklearn.tree.export_graphviz). This is more of a lagacy method, and it is not recommended to use it in new projects. Instead, use sklearn's built in method such as sklearn.tree.plot_tree.
from ds_utils.xai import draw_dot_data
from sklearn.tree import export_graphviz
import matplotlib.pyplot as plt
# complete usage example
dot = export_graphviz(clf, feature_names=features, class_names=["no", "yes"], filled=True, rounded=True, out_file=None)
draw_dot_data(dot)
plt.show()
Parameters:
dot_data- str, Graphviz DOT string to render.ax- matplotlib Axes, optional. Target axes for rendering.
Returns: matplotlib Axes.
Common mistakes:
- Passing an empty DOT string.
draw_dot_datarequires a non-empty valid Graphviz DOT payload. - Passing the estimator object directly; first generate DOT text using
export_graphviz(..., out_file=None).
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier
from ds_utils.xai import plot_features_importance
features = ["age", "income", "credit_score"]
clf = DecisionTreeClassifier(random_state=42)
clf.fit(X_train[features], y_train)
# Feature importance bar chart
plot_features_importance(features, clf.feature_importances_)
plt.tight_layout()
plt.show()