Package: pyCeterisParibus
pyCeterisParibuspyCeterisParibus is a Python library based on anRpackageCeterisParibus.
It implements Ceteris Paribus Plots.
They allow understanding how the model response would change if a selected variable is changed.
It’s a perfect tool for What-If scenarios. Ceteris Paribus is a Latin phrase meaning all else unchanged.
These plots present the change in model response as the values of one feature change with all others being fixed.
Ceteris Paribus method is model-agnostic - it works for any Machine Learning model.
The idea is an extension of PDP (Partial Dependency Plots) and ICE (Individual Conditional Expectations) plots.
It allows explaining single observations for multiple variables at the same time.
The plot engine is developedhere.Why is it so useful?There might be several motivations behind utilizing this idea.
Imagine a person gets a low credit score.
The client wants to understand how to increase the score and the scoring institution (e.g. a bank) should be able to answer such questions.
Moreover, this method is useful for researchers and developers to analyze, debug, explain and improve Machine Learning models, assisting the entire process of the model design.SetupTested on Python 3.5+PyCeterisParibus is onPyPI. Simply run:pipinstallpyCeterisParibusor install the newest version from GitHub by executing:pipinstallgit+https://github.com/ModelOriented/pyCeterisParibusor download the sources, enter the main directory and perform:https://github.com/ModelOriented/pyCeterisParibus.gitcdpyCeterisParibus
pythonsetup.pyinstall# (alternatively use pip install .)DocsA detailed description of all methods and their parameters might be found indocumentation.To build the documentation locally:pipinstall-rrequirements-dev.txtcddocs
makehtmland open_build/html/index.htmlExamplesBelow we present use cases on two well-known datasets - Titanic and Iris. More examples e.g. for regression problems might be foundhereand in jupyter notebookshere.Note, that in order to run the examples you need to install extra requirements fromrequirements-dev.txt.Use case - Titanic survivalWe demonstrate Ceteris Paribus Plots using the well-known Titanic dataset. In this problem, we examine the chance of survival for Titanic passengers.
We start with preprocessing the data and creating an XGBoost model.importpandasaspddf=pd.read_csv('titanic_train.csv')y=df['Survived']x=df.drop(['Survived','PassengerId','Name','Cabin','Ticket'],inplace=False,axis=1)valid=x['Age'].isnull()|x['Embarked'].isnull()x=x[-valid]y=y[-valid]fromsklearn.model_selectionimporttrain_test_splitX_train,X_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=42)fromsklearn.pipelineimportPipelinefromsklearn.preprocessingimportStandardScaler,OneHotEncoderfromsklearn.composeimportColumnTransformer# We create the preprocessing pipelines for both numeric and categorical data.numeric_features=['Pclass','Age','SibSp','Parch','Fare']numeric_transformer=Pipeline(steps=[('scaler',StandardScaler())])categorical_features=['Embarked','Sex']categorical_transformer=Pipeline(steps=[('onehot',OneHotEncoder(handle_unknown='ignore'))])preprocessor=ColumnTransformer(transformers=[('num',numeric_transformer,numeric_features),('cat',categorical_transformer,categorical_features)])fromxgboostimportXGBClassifierxgb_clf=Pipeline(steps=[('preprocessor',preprocessor),('classifier',XGBClassifier())])xgb_clf.fit(X_train,y_train)Here the pyCeterisParibus starts. Since this library works in a model agnostic fashion, first we need to create a wrapper around the model with uniform predict interface.fromceteris_paribus.explainerimportexplainexplainer_xgb=explain(xgb_clf,data=x,y=y,label='XGBoost',predict_function=lambdaX:xgb_clf.predict_proba(X)[::,1])Single variable profileLet's look at Mr Ernest James Crease, the 19-year-old man, travelling on the 3. class from Southampton with an 8 pounds ticket in his pocket. He died on Titanic. Most likely, this would not have been the case had Ernest been a few years younger.
Figure 1 presents the chance of survival for a person like Ernest at different ages. We can see things were tough for people like him unless they were a child.ernest=X_test.iloc[10]label_ernest=y_test.iloc[10]fromceteris_paribus.profilesimportindividual_variable_profilecp_xgb=individual_variable_profile(explainer_xgb,ernest,label_ernest)Having calculated the profile we can plot it. Note, thatplot_notebookmight be used instead ofplotwhen used in Jupyter notebooks.fromceteris_paribus.plots.plotsimportplotplot(cp_xgb,selected_variables=["Age"])Many modelsThe above picture explains the prediction of XGBoost model. What if we compare various models?fromsklearn.ensembleimportRandomForestClassifierfromsklearn.linear_modelimportLogisticRegressionrf_clf=Pipeline(steps=[('preprocessor',preprocessor),('classifier',RandomForestClassifier())])linear_clf=Pipeline(steps=[('preprocessor',preprocessor),('classifier',LogisticRegression())])rf_clf.fit(X_train,y_train)linear_clf.fit(X_train,y_train)explainer_rf=explain(rf_clf,data=x,y=y,label='RandomForest',predict_function=lambdaX:rf_clf.predict_proba(X)[::,1])explainer_linear=explain(linear_clf,data=x,y=y,label='LogisticRegression',predict_function=lambdaX:linear_clf.predict_proba(X)[::,1])plot(cp_xgb,cp_rf,cp_linear,selected_variables=["Age"])Clearly, XGBoost offers a better fit than Logistic Regression.
Also, it predicts a higher chance of survival at child's age than the Random Forest model does.Profiles for many variablesThis time we have a look at Miss. Elizabeth Mussey Eustis. She is 54 years old, travels at 1. class with her sister Marta, as they return to the US from their tour of southern Europe. They both survived the disaster.elizabeth=X_test.iloc[1]label_elizabeth=y_test.iloc[1]cp_xgb_2=individual_variable_profile(explainer_xgb,elizabeth,label_elizabeth)plot(cp_xgb_2,selected_variables=["Pclass","Sex","Age","Embarked"])Would she have returned home if she had travelled at 3. class or if she had been a man? As we can observe this is less likely. On the other hand, for a first class, female passenger chances of survival were high regardless of age. Note, this was different in the case of Ernest. Place of embarkment (Cherbourg) has no influence, which is expected behaviour.Feature interactions and average responseNow, what if we look at passengers most similar to Miss. Eustis (middle-aged, upper class)?fromceteris_paribus.select_dataimportselect_neighboursneighbours=select_neighbours(X_train,elizabeth,selected_variables=['Pclass','Age','SibSp','Parch','Fare','Embarked'],n=15)cp_xgb_ns=individual_variable_profile(explainer_xgb,neighbours)plot(cp_xgb_ns,color="Sex",selected_variables=["Pclass","Age"],aggregate_profiles='mean',size_pdps=6,alpha_pdps=1,size=2)There are two distinct clusters of passengers determined with their gender, therefore aPDPaverage plot (on grey) does not show the whole picture. Children of both genders were likely to survive, but then we see a large gap. Also, being female increased the chance of survival mostly for second and first class passengers.Plot function comes with extensive customization options. List of all parameters might be found in the documentation. Additionally, one can interact with the plot by hovering over a point of interest to see more details. Similarly, there is an interactive table with options for highlighting relevant elements as well as filtering and sorting rows.Multiclass models - Iris datasetPrepare dataset and modeliris=load_iris()defrandom_forest_classifier():rf_model=RandomForestClassifier(n_estimators=100,random_state=42)rf_model.fit(iris['data'],iris['target'])returnrf_model,iris['data'],iris['target'],iris['feature_names']Wrap model into explainersrf_model,iris_x,iris_y,iris_var_names=random_forest_classifier()explainer_rf1=explain(rf_model,iris_var_names,iris_x,iris_y,predict_function=lambdaX:rf_model.predict_proba(X)[::,0],label=iris.target_names[0])explainer_rf2=explain(rf_model,iris_var_names,iris_x,iris_y,predict_function=lambdaX:rf_model.predict_proba(X)[::,1],label=iris.target_names[1])explainer_rf3=explain(rf_model,iris_var_names,iris_x,iris_y,predict_function=lambdaX:rf_model.predict_proba(X)[::,2],label=iris.target_names[2])Calculate profiles and plotcp_rf1=individual_variable_profile(explainer_rf1,iris_x[0],iris_y[0])cp_rf2=individual_variable_profile(explainer_rf2,iris_x[0],iris_y[0])cp_rf3=individual_variable_profile(explainer_rf3,iris_x[0],iris_y[0])plot(cp_rf1,cp_rf2,cp_rf3,selected_variables=['petal length (cm)','petal width (cm)','sepal length (cm)'])ContributingYou're more than welcomed to contribute to this package. See theguideline.AcknowledgmentsWork on this package was financially supported by the ‘NCN Opus grant 2016/21/B/ST6/0217’.