Contributions plot#
contribution_plot displays a violin or scatter plot to show how a feature affects the predictions.
This tutorial presents the parameters you can use to tune its output.
Contents:
Classification case: choose the target class to display
Sampling parameter
Focus on a subset
Choose between violin and scatter plots
Data from Kaggle Titanic
import pandas as pd
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
from shapash.utils.dtypes import text_like_columns
Build a supervised model#
Load Titanic data
from shapash.data.data_loader import data_loading
titanic_df, titanic_dict = data_loading("titanic")
y_df = titanic_df["Survived"].to_frame()
X_df = titanic_df[titanic_df.columns.difference(["Survived"])]
titanic_df.head()
| Survived | Pclass | Name | Sex | Age | SibSp | Parch | Fare | Embarked | Title | |
|---|---|---|---|---|---|---|---|---|---|---|
| PassengerId | ||||||||||
| 1 | 0 | Third class | Braund Owen Harris | male | 22.0 | 1 | 0 | 7.25 | Southampton | Mr |
| 2 | 1 | First class | Cumings John Bradley (Florence Briggs Thayer) | female | 38.0 | 1 | 0 | 71.28 | Cherbourg | Mrs |
| 3 | 1 | Third class | Heikkinen Laina | female | 26.0 | 0 | 0 | 7.92 | Southampton | Miss |
| 4 | 1 | First class | Futrelle Jacques Heath (Lily May Peel) | female | 35.0 | 1 | 0 | 53.10 | Southampton | Mrs |
| 5 | 0 | Third class | Allen William Henry | male | 35.0 | 0 | 0 | 8.05 | Southampton | Mr |
Encode categorical features
from category_encoders import OrdinalEncoder
categorical_features = text_like_columns(X_df, strict_object=False)
encoder = OrdinalEncoder(cols=categorical_features, handle_unknown="return_nan", return_df=True).fit(X_df)
X_df = encoder.transform(X_df)
Split train and test sets, then fit the model
Xtrain, Xtest, ytrain, ytest = train_test_split(X_df, y_df, train_size=0.75, random_state=7)
clf = XGBClassifier(n_estimators=200, min_child_weight=2).fit(Xtrain, ytrain)
Compile the SmartExplainer#
from shapash.explainer.smart_explainer import SmartExplainer
response_dict = {0: "Death", 1: " Survival"}
xpl = SmartExplainer(
model=clf,
preprocessing=encoder, # Optional: compile step can use inverse_transform method
features_dict=titanic_dict, # Optional parameters
label_dict=response_dict,
) # Optional parameters, dicts specify labels
xpl.compile(x=Xtest)
INFO: Shap explainer type - <shap.explainers._tree.TreeExplainer object at 0x7f836390ae20>
Contribution plot#
Specify the feature to analyze with its column name, label or column number.
fig = xpl.plot.contribution_plot(col="Age")
fig.to_image(format="png")
xpl.plot.contribution_plot(col="Pclass")
Ticket class seems to affect the model’s predictions: third class contributes negatively to survival.
Classification: choose the target class#
With the label parameter, you can specify the label value or its number.
xpl.plot.contribution_plot(col="Pclass", label="Death")
Add a prediction to better understand your model#
You can add your predictions with the add or compile method.
y_pred = pd.DataFrame(clf.predict(Xtest), columns=["pred"], index=Xtest.index)
xpl.add(y_pred=y_pred)
xpl.plot.contribution_plot(col="Pclass")
With the predictions added, you can see that the contribution of Ticket class for First class and Second class seems different for people predicted to survive (orange points) than for the others (grey points). The contributions for these two ticket classes may be correlated with the value of another feature.
The Shapash webapp can help you refine your understandingof the model. You can navigate between the local and the global contributions.
For third class, the 2 distributions look similar.
Note (multiclass): this plot shows a one-vs-all view.
Focus on a subset#
With the selection parameter, you can specify a list of indices of the people you want to focus on.
index = list(Xtest[xpl.explainer.x_init["Pclass"].isin(["First class", "Second class"])].index.values)
xpl.plot.contribution_plot(col="Pclass", selection=index)
Size of the random sample#
contribution_plot uses a random sample to limit the number of points displayed. The default sample size is 2000; you can change it with the max_points parameter:
xpl.plot.contribution_plot(col="Pclass", max_points=50)
Violin or scatter plot?#
contribution_plot displays a scatter plot when the feature has more than 10 distinct values. You can change this threshold with the violin_maxf parameter:
fig = xpl.plot.contribution_plot(col="Pclass", violin_maxf=2)