shapash

repository·master·Indexed 25 days ago

https://github.com/maif/shapash

A Python library for machine learning interpretability designed to make models understandable for both technical and non-technical stakeholders. It provides tools for global and local explainability, including the SmartExplainer for generating interactive web applications and comprehensive HTML audit reports. Shapash supports Regression, Binary Classification, and Multiclass problems, and is compatible with Catboost, Xgboost, LightGBM, Sklearn Ensemble, Linear models, and SVM.

Tokens
11.7K
Snippets
29
Records
56
Agent score
85%

What's inside shapash

  1. Overview of Shapash

    master

    Shapash is a Python library designed to make machine learning models interpretable and comprehensible. It provides visualizations with clear labels to help both data scientists and non-experts understand model behavior.

    Key capabilities include:

    • Webapp Generation: Simplifies understanding feature interactions and enables navigation between local and global explainability.
    • Model Auditing: Generates comprehensive reports to provide valuable information about models and data.
    • Problem Support: Suitable for Regression, Binary Classification, and Multiclass problems.
    • Model Compatibility: Works with Catboost, Xgboost, LightGBM, Sklearn Ensemble, Linear models, and SVM. Other models can be integrated using custom solutions.
  2. Overview of tarteaucitron.js functionality

    master

    tarteaucitron.js is a script designed to comply with European cookie laws by managing third-party service consent.

    Key behaviors include:

    • Default State: Disables all services by default.
    • Consent UI: Displays a banner on the first page view and a smaller version on subsequent pages, plus a panel for granular service control (allow/deny).
    • Activation: Services are activated on the second page view if consent was not denied.
    • Persistence: Stores user consent in a cookie for 365 days.
    • Performance: Loads services immediately upon user click without requiring a page reload.
    • Fallbacks: Provides fallback systems, such as displaying links instead of social buttons or static banners instead of advertising.
  3. Overview of Shapash features and capabilities

    master

    Shapash is a Python library designed to make machine learning models interpretable and accessible. It provides both global and local explainability through various visualizations and a web application (shapash-monitor).

    Key Capabilities:

    • Explainability: Supports global and local visualizations using Shap and Lime backends. Compatible with Regression, Binary Classification, and Multiclass problems.
    • Model Compatibility: Works with most sklearn, lightgbm, catboost, and xgboost models.
    • Local Summarization: Summarizes local explanations into concise, transparent formats and exports them as Pandas DataFrames.
    • Data Handling: Uses encoder objects and feature dictionaries for clear labeling; compatible with category_encoders and Sklearn ColumnTransformer.
    • Operational Use: Suitable for both exploration and deployment via API or Batch mode.
    • Auditability: Allows freezing aspects of a data science project to establish a foundation for audit reports.
  4. Compatible models and dependencies for Shapash

    master

    Shapash is an overlay package for model interpretability libraries (using Shap or Lime backends). It supports Regression, Binary Classification, and Multiclass problems.

    Supported Models:

    • Catboost
    • Xgboost
    • LightGBM
    • Sklearn Ensemble
    • Linear models
    • SVM

    Supported Preprocessing/Encoders:

    • Category_encoder: OneHotEncoder, OrdinalEncoder, BaseNEncoder, BinaryEncoder, or TargetEncoder
    • Sklearn ColumnTransformer: OneHotEncoder, OrdinalEncoder, StandardScaler, QuantileTransformer, or PowerTransformer

    Compatible Dependency Versions:

    • scikit-learn==0.23.2
    • catboost==0.22
    • xgboost==1.0.0
    • lightgbm==2.3.1
    • shap==0.37.0
    • category-encoders==2.1.0
  5. Use the SmartPredictor object for model explanations

    master

    The SmartPredictor object is the primary interface for computing predictions, configuring local explanation summaries, and deploying model interpretability for operational needs. It supports both API mode and batch mode.

    Key capabilities include:

    • Computing predictions (predict, predict_proba).
    • Configuring summaries of local explanations (summarize).
    • Detailing feature contributions (detail_contributions).
    • Modifying masks (modify_mask).
    • Saving the predictor state (save).
    • Adding input data (add_input).
  6. Quickstart: Use SmartExplainer to analyze a model

    master

    Follow these four steps to initialize an explainer, compile your data, and view results.

    1. Declare the SmartExplainer object

    Initialize the explainer with your model. You can optionally provide a features_dict for labels, a preprocessing object (which should have an inverse_transform method), and a postprocessing function.

    2. Compile the dataset

    Use the .compile() method to link your data to the explainer. Mandatory parameter is x (the dataset).

    3. Display output

    Launch the interactive web application using .run_app().

    4. Generate a Shapash Report

    Create a standalone HTML report containing project metrics and data splits using .generate_report().

    from shapash import SmartExplainer
    
    # Step 1: Declare SmartExplainer Object
    xpl = SmartExplainer(
      features_dict=house_dict,  # Optional
      model=regressor,           # Mandatory
      preprocessing=encoder,     # Optional
      postprocessing=postprocess # Optional
    )
    
    # Step 2: Compile Dataset
    xpl.compile(
        x=Xtest,
        y_pred=y_pred,               # Optional
        y_target=yTest,              # Optional
        additional_data=X_additional, # Optional
        additional_features_dict=features_dict_additional, # Optional
    )
    
    # Step 3: Display output (Web App)
    app = xpl.run_app()
    
    # Step 4: Generate the Shapash Report
    xpl.generate_report(
        output_file='path/to/output/report.html',
        project_info_file='path/to/project_info.yml',
        x_train=Xtrain,
        y_train=ytrain,
        y_test=ytest,
        title_story="House prices report",
        title_description="""This document is a data science report of the kaggle house prices tutorial project. It was generated using the Shapash library.
                """,
        metrics=[{'name': 'MSE', 'path': 'sklearn.metrics.mean_squared_error'}]
    )
  7. Quickstart: Use SmartExplainer to analyze models

    master

    To perform model interpretability, follow these steps using the SmartExplainer class:

    1. Initialize SmartExplainer: Pass your trained model. You can optionally provide a features_dict for custom labels, a preprocessing object (which should have an inverse_transform method), and a postprocessing function.
    2. Compile the dataset: Use the .compile() method to provide the test data (x), predictions (y_pred), and target values (y_target). You can also include additional_data for the webapp and additional_features_dict for extra context.
    3. Display results: Launch an interactive web application using .run_app().
    4. Generate a report: Create a standalone HTML audit report using .generate_report().
    from shapash import SmartExplainer
    
    # Step 1: Declare SmartExplainer Object
    xpl = SmartExplainer(
        model=regressor,
        features_dict=house_dict,  # Optional
        preprocessing=encoder,      # Optional
        postprocessing=postprocess,  # Optional
    )
    
    # Step 2: Compile Dataset
    xpl.compile(
        x=xtest,
        y_pred=y_pred,              # Optional
        y_target=yTest,            # Optional
        additional_data=xadditional,  # Optional
        additional_features_dict=features_dict_additional,  # Optional
    )
    
    # Step 3: Display output (Webapp)
    app = xpl.run_app()
    
    # Step 4: Generate the Shapash Report
    xpl.generate_report(
        output_file="path/to/output/report.html",
        project_info_file="path/to/project_info.yml",
        x_train=xtrain,
        y_train=ytrain,
        y_test=ytest,
        title_story="House prices report",
        title_description="""This document is a data science report...""",
        metrics=[{"name": "MSE", "path": "sklearn.metrics.mean_squared_error"}],
    )
  8. Configure Jupyter for inline graphs

    master

    To display inline graphs in Jupyter, you must install ipywidgets.

    Standard Installation

    Use pip or conda:

    pip install ipywidgets
    # OR
    conda install -c conda-forge ipywidgets

    Jupyter Notebook (Classic)

    If widgets do not appear automatically, you may need to manually enable the extension:

    jupyter nbextension enable --py widgetsnbextension

    If using a virtual environment, use the --sys-prefix flag to keep the environment isolated:

    jupyter nbextension enable --py widgetsnbextension --sys-prefix

    JupyterLab 3

    JupyterLab 3 uses jupyterlab_widgets (version 1.0+) for widget support. If your JupyterLab server and IPython kernel are in different environments, follow these steps:

    1. Install jupyterlab_widgets in the environment containing the JupyterLab server.
    2. Install ipywidgets in each kernel's environment.

    Example for conda:

    conda install -n base -c conda-forge jupyterlab_widgets
    conda install -n <your_kernel_env> -c conda-forge ipywidgets

    To enable Plotly in JupyterLab, install both the plotly package and the labextension:

    conda install -c plotly plotly
    jupyter labextension install jupyterlab-plotly
  9. Access Shapash Documentation and Resources

    master

    For detailed usage, tutorials, and deep dives, refer to the following resources:

    • Official Documentation: Readthedocs
    • Live Demo: Shapash App Demo
    • Community Articles: Various guides are available on Medium (Towards AI and Towards Data Science) covering topics like model auditability, feature grouping, and explainability quality metrics.
  10. Install Shapash

    master
    Shapash is compatible with Python versions 3.11 to 3.14. You can install the core package using pip. If you intend to generate standalone HTML reports, you must install the [report] extra to include the necessary dependencies.
  11. Configure JupyterLab 1 or 2 for inline graphs

    master

    JupyterLab 1 or 2 requires nodejs and a manual labextension installation to display widgets.

    1. Install nodejs (e.g., via conda):
      conda install -c conda-forge nodejs
    2. Install the manager extension:
      jupyter labextension install @jupyter-widgets/jupyterlab-manager

    Note: If you install the extension while JupyterLab is running, you must refresh the page or restart JupyterLab.

    To enable Plotly in JupyterLab 1 or 2:

    conda install -c plotly plotly
    jupyter labextension install jupyterlab-plotly