### Install ExplainerDashboard Source: https://github.com/oegedijk/explainerdashboard/blob/master/notebooks/custom_examples.ipynb Install the library via pip. ```python #!pip install explainerdashboard ``` -------------------------------- ### Install Explainer Dashboard Source: https://context7.com/oegedijk/explainerdashboard/llms.txt Install the explainerdashboard library using pip. ```bash pip install explainerdashboard ``` -------------------------------- ### Example Usage Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/dashboards.md Examples of how to run and terminate the ExplainerDashboard. ```APIDOC ### Example ExplainerDashboard(explainer, mode=’external’).run(port=8050) ExplainerDashboard.terminate(8050) ``` -------------------------------- ### run() Method Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/dashboards.md Starts the ExplainerDashboard on a specified port. ```APIDOC ## run(port: int = None, host: str = '0.0.0.0', use_waitress: bool = False, mode: str = None, sagemaker: bool | None = None, **kwargs) ### Description Start ExplainerDashboard on port. ### Parameters #### Parameters * **port** (*int*, optional) – port to run on. If None, then use self.port. * **host** (*str*, optional) – host to run on. Defaults to ‘0.0.0.0’. * **use_waitress** (*bool*, optional) – use the waitress python web server instead of the flask development server. Only works with mode=’dash’. Defaults to False. * **mode** (*str*, {'dash', 'inline', 'jupyterlab', 'external'}, optional) – Type of dash server to start. ‘inline’ runs in a jupyter notebook output cell. ‘jupyterlab’ runs in a jupyterlab pane. ‘external’ runs in an external tab while keeping the notebook interactive. ‘dash’ is the default server. Overrides self.mode, in which case the dashboard will get rebuilt before running it with the right type of dash server. (dash.Dash or JupyterDash). Defaults to None (i.e. self.mode) * **sagemaker** (*bool*, optional) – if True, apply SageMaker Studio proxy defaults for routes_pathname_prefix and requests_pathname_prefix. If None, use the value from the dashboard initialization. * **8050.** (*Defaults to None.self.port defaults to*) ### Raises **ValueError** – if mode is unknown ``` -------------------------------- ### Install explainerdashboard via pip or conda Source: https://github.com/oegedijk/explainerdashboard/blob/master/README.md Use these commands to install the package in your environment. ```bash pip install explainerdashboard ``` ```bash conda install -c conda-forge explainerdashboard ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/oegedijk/explainerdashboard/blob/master/CONTRIBUTING.md Upgrade core packaging tools and install the project in editable mode. ```bash $ python -m pip install -U pip setuptools wheel $ pip install -e . ``` -------------------------------- ### Run ExplainerDashboard Source: https://github.com/oegedijk/explainerdashboard/blob/master/notebooks/dashboard_examples.ipynb Instantiate the dashboard with a fitted classifier and start the server. ```python ExplainerDashboard( ClassifierExplainer(RandomForestClassifier().fit(X_train, y_train), X_test, y_test) ).run() ``` -------------------------------- ### Initialize and run ExplainerHub Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/hub.md Creates a hub instance with multiple dashboards and authentication, then starts the server. ```python hub = ExplainerHub([db1, db2], logins=[['user', 'password']], secret_key="SECRET") hub.run() ``` -------------------------------- ### Run ExplainerDashboard Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/explainers.md Launch an ExplainerDashboard with a pre-initialized explainer instance. This is the most basic way to start the dashboard. ```python from explainerdashboard import ExplainerDashboard ExplainerDashboard(explainer).run() ``` -------------------------------- ### Custom Dashboard Example Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/components.md An example demonstrating how to build a custom dashboard using ExplainerComponent and ShapDependenceComponent. ```APIDOC ## Custom Dashboard Example ### Description This example shows how to create a custom dashboard layout using `ExplainerComponent` and `ShapDependenceComponent`. It demonstrates initializing a component with specific configurations like hiding titles and categories, and setting an initial feature. ### Code ```python from explainerdashboard.custom import * class CustomDashboard(ExplainerComponent): def __init__(self, explainer, title="Custom Dashboard", name="None"): super().__init__(explainer, title, name=name) self.shap_dependence = ShapDependenceComponent(explainer, name=self.name+"dep", hide_title=True, hide_cats=True, hide_highlight=True, cats=True, col='Fare') def layout(self): return html.Div([ self.shap_dependence.layout() ]) ExplainerDashboard(explainer, CustomDashboard).run() ``` ``` -------------------------------- ### Run ExplainerDashboard Source: https://github.com/oegedijk/explainerdashboard/blob/master/notebooks/dashboard_examples.ipynb Starts the dashboard server for the provided explainer instance. ```python ExplainerDashboard(explainer).run() ``` -------------------------------- ### Run ExplainerHub via CLI Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/hub.md Starts the hub server using the command line interface. ```bash $ explainerhub run hub.yaml ``` -------------------------------- ### Extended example with model training and dashboard configuration Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/index.md A complete workflow including data loading, model training, explainer construction, and dashboard customization. ```python from sklearn.ensemble import RandomForestClassifier from explainerdashboard import ClassifierExplainer, ExplainerDashboard from explainerdashboard.datasets import titanic_survive X_train, y_train, X_test, y_test = titanic_survive() model = RandomForestClassifier(n_estimators=50, max_depth=5) model.fit(X_train, y_train) explainer = ClassifierExplainer( model, X_test, y_test, # optional: cats=['Sex', 'Deck', 'Embarked'], labels=['Not survived', 'Survived']) db = ExplainerDashboard(explainer, title="Titanic Explainer", whatif=False, # you can switch off tabs with bools shap_interaction=False, decision_trees=False) db.run(port=8051) ``` -------------------------------- ### Initialize and Run the Dash App Source: https://github.com/oegedijk/explainerdashboard/blob/master/notebooks/custom_examples.ipynb Register component callbacks to the Dash app instance and start the server. ```python app = JupyterDash( __name__, external_stylesheets=[dbc.themes.FLATLY], assets_url_path="" ) app.title = "Titanic Explainer" app.layout = layout precision.register_callbacks(app) shap_summary.register_callbacks(app) shap_dependence.register_callbacks(app) connector.register_callbacks(app) app.run_server(port=8050) ``` -------------------------------- ### Install Testing Dependencies Source: https://github.com/oegedijk/explainerdashboard/blob/master/CONTRIBUTING.md Install additional libraries required for running the full test suite. ```bash $ pip install -r requirements_testing.txt ``` -------------------------------- ### ClassifierExplainer Usage Example Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/explainers.md Example demonstrating how to initialize a ClassifierExplainer and invoke various plotting methods. ```default explainer = ClassifierExplainer(model, X, y, labels=['Not Survived', 'Survived']) explainer.plot_confusion_matrix(cutoff=0.6) explainer.plot_precision(quantiles=10, cutoff=0.6, multiclass=True) explainer.plot_lift_curve(percentage=True) explainer.plot_roc_auc(cutoff=0.7) explainer.plot_pr_auc(cutoff=0.3) ``` -------------------------------- ### Example YAML Configuration Structure Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/hub.md The structure of the generated hub.yaml file containing dashboard references and settings. ```default explainerhub: title: ExplainerHub description: Showing dashboards for both model one and two masonry: false n_dashboard_cols: 3 users_file: users.yaml db_users: null port: 8050 kwargs: {} dashboards: - db1_dashboard.yaml - db2_dashboard.yaml ``` -------------------------------- ### Heroku Procfile Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/deployment.md Define the command to start your web server in the `Procfile`. This tells Heroku how to launch your application. ```bash web: gunicorn dashboard:app ``` -------------------------------- ### Run Dashboard with Production Servers Source: https://github.com/oegedijk/explainerdashboard/blob/master/README.md Commands to start the dashboard application using Gunicorn or Waitress. ```sh $ gunicorn dashboard:app ``` ```sh $ waitress-serve dashboard:app ``` -------------------------------- ### Run dashboard with Gunicorn Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/dashboards.md Command to start the dashboard server using Gunicorn. ```bash gunicorn dashboard:server ``` -------------------------------- ### Run dashboard with Waitress Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/dashboards.md Command to start the dashboard server using Waitress on Windows. ```bash waitress-serve dashboard:server ``` -------------------------------- ### Deploying to Kubernetes (Ingress) Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/index.md Configuration details for deploying an ExplainerDashboard behind a Kubernetes Ingress controller. This example shows a basic Ingress resource definition. ```yaml apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: explainer-ingress spec: rules: - host: explainer.yourdomain.com http: paths: - path: / pathType: Prefix backend: service: name: explainer-service port: number: 8080 ``` -------------------------------- ### Run Dashboard with Gunicorn (Basic) Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/deployment.md Start the gunicorn server to host your dashboard. Ensure your Flask app is exposed as 'app' in 'dashboard.py'. ```bash $ gunicorn dashboard:app ``` -------------------------------- ### Alternative Regression Models Source: https://github.com/oegedijk/explainerdashboard/blob/master/notebooks/dashboard_examples.ipynb Examples of importing and initializing various regression models for use with the dashboard. ```python from lightgbm.sklearn import LGBMRegressor model = LGBMRegressor() # from sklearn.linear_model import LinearRegression # model = LinearRegression() # from catboost import CatBoostRegressor # model = CatBoostRegressor(iterations=100, learning_rate=0.1, verbose=0) # from xgboost import XGBRegressor ``` -------------------------------- ### Run the ExplainerDashboard Source: https://github.com/oegedijk/explainerdashboard/blob/master/notebooks/simplified_classifier_dashboard_example.ipynb Start the ExplainerDashboard on a specified port. The dashboard will be accessible via the provided URL. Ensure the port is not in use. ```python db.run(port=9000) ``` -------------------------------- ### ExplainerDashboard Startup Output Source: https://github.com/oegedijk/explainerdashboard/blob/master/notebooks/dashboard_examples.ipynb This output shows the typical messages displayed when ExplainerDashboard starts, including environment detection, layout generation, and server startup information. ```text Building ExplainerDashboard..\nDetected notebook environment, consider setting mode='external', mode='inline' or mode='jupyterlab' to keep the notebook interactive while the dashboard is running...\nGenerating layout...\nCalculating dependencies...\nReminder: you can store the explainer (including calculated dependencies) with explainer.dump('explainer.joblib') and reload with e.g. ClassifierExplainer.from_file('explainer.joblib')\nRegistering callbacks...\nStarting ExplainerDashboard on http://localhost:8050\nDash is running on http://0.0.0.0:8050/\n\nDash is running on http://0.0.0.0:8050/\n\nDash is running on http://0.0.0.0:8050/\n\n * Serving Flask app "explainerdashboard.dashboards" (lazy loading)\n * Environment: production\n\u001B[31m WARNING: This is a development server. Do not use it in a production deployment.\n\u001B[2m Use a production WSGI server instead.\n * Debug mode: off\n\n ``` -------------------------------- ### Run a basic ClassifierExplainer dashboard Source: https://github.com/oegedijk/explainerdashboard/blob/master/README.md A minimal example to fit a model and launch the dashboard in one line. ```python ExplainerDashboard(ClassifierExplainer(RandomForestClassifier().fit(X_train, y_train), X_test, y_test)).run() ``` -------------------------------- ### Create a Custom Dashboard with ShapDependenceComponent Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/components.md Example of subclassing ExplainerComponent to build a custom dashboard layout with specific component configurations. ```python from explainerdashboard.custom import * class CustomDashboard(ExplainerComponent): def __init__(self, explainer, title="Custom Dashboard", name="None"): super().__init__(explainer, title, name=name) self.shap_dependence = ShapDependenceComponent(explainer, name=self.name+"dep", hide_title=True, hide_cats=True, hide_highlight=True, cats=True, col='Fare') def layout(self): return html.Div([ self.shap_dependence.layout() ]) ExplainerDashboard(explainer, CustomDashboard).run() ``` -------------------------------- ### Standalone Dockerfile for ExplainerDashboard Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/deployment.md Dockerfile for a standalone ExplainerDashboard deployment. Installs the library, copies scripts, generates the dashboard, and sets the run command. ```docker FROM python:3.8 RUN pip install explainerdashboard COPY generate_dashboard.py ./ COPY run_dashboard.py ./ RUN python generate_dashboard.py EXPOSE 9050 CMD ["python", "./run_dashboard.py"] ``` -------------------------------- ### Hugging Face Space Dockerfile Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/deployment.md Dockerfile for deploying an ExplainerDashboard to Hugging Face Spaces. Installs dependencies and sets up the application server. ```docker FROM python:3.11-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . EXPOSE 7860 CMD ["gunicorn", "dashboard:app", "--bind", "0.0.0.0:7860"] ``` -------------------------------- ### ExplainerDashboard Startup Output (Instance) Source: https://github.com/oegedijk/explainerdashboard/blob/master/notebooks/dashboard_examples.ipynb This output is similar to the previous startup output, indicating the dashboard is building, detecting the environment, and preparing to run. ```text Building ExplainerDashboard..\nDetected notebook environment, consider setting mode='external', mode='inline' or mode='jupyterlab' to keep the notebook interactive while the dashboard is running...\nGenerating layout...\nCalculating dependencies...\nReminder: you can store the explainer (including calculated dependencies) with explainer.dump('explainer.joblib') and reload with e.g. ClassifierExplainer.from_file('explainer.joblib')\nRegistering callbacks...\nStarting ExplainerDashboard on http://localhost:8050\nDash is running on http://0.0.0.0:8050/\n\nDash is running on http://0.0.0.0:8050/\n\nDash is running on http://0.0.0.0:8050/\n\nDash is running on http://0.0.0.0:8050/\n\n * Serving Flask app "explainerdashboard.dashboards" (lazy loading)\n * Environment: production\n\u001B[31m WARNING: This is a development server. Do not use it in a production deployment.\n\u001B[2m Use a production WSGI server instead.\n * Debug mode: off\n\n ``` -------------------------------- ### Load dashboard from configuration Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/deployment.md Initializes an ExplainerDashboard instance directly from a previously saved configuration file. ```python from explainerdashboard import ExplainerDashboard db = ExplainerDashboard.from_config("dashboard.yaml") app = db.app.server ``` -------------------------------- ### Get Importances DataFrame Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/explainers.md A wrapper function to get feature importances, either as SHAP values or permutation importances. ```APIDOC ## get_importances_df(kind='shap', topx=None, cutoff=None, pos_label=None) ### Description A wrapper function for `get_mean_abs_shap_df()` and `get_permutation_importance_df()`. It allows retrieving feature importances based on either SHAP values or permutation importance. ### Method Not applicable (this is a method call within an instance) ### Parameters #### Path Parameters None #### Query Parameters * **kind** (str) - Specifies the type of importance to retrieve. Accepts 'shap' or 'permutations'. Defaults to 'shap'. * **topx** (int, optional) - Only display the `topx` highest features. Defaults to None. * **cutoff** (float, optional) - Only display features with importance above `cutoff`. Defaults to None. * **pos_label** (any, optional) - The positive class label. Defaults to None. ### Request Example ```python shap_importances = explainer.get_importances_df(kind='shap', topx=5) permutation_importances = explainer.get_importances_df(kind='permutations', cutoff=0.05) ``` ### Response #### Success Response (200) * **pd.DataFrame** - A DataFrame containing the requested feature importances. #### Response Example ```json { "feature1": 0.45, "feature2": 0.28, "feature3": 0.15 } ``` ``` -------------------------------- ### Initialize default ExplainerDashboard Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/dashboards.md Construct an Explainer instance and launch the dashboard with default compatible tabs. ```python from explainerdashboard import ClassifierExplainer, ExplainerDashboard explainer = ClassifierExplainer(model, X_test, y_test) ExplainerDashboard(explainer).run() ``` -------------------------------- ### Custom Model Tab Example Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/index.md Defines a custom tab for displaying model-specific information. This example shows how to create a new tab that can be integrated into the ExplainerDashboard. ```python from explainerdashboard.custom import ExplainerComponent from dash import html class CustomModelTab(ExplainerComponent): def __init__(self, name, explainer, **kwargs): super().__init__(name=name, explainer=explainer, **kwargs) def _layout(self): return html.Div([ html.H3("Custom Model Information"), html.P(f"Model index: {self.explainer.model_output_names()[0]}") ]) ``` -------------------------------- ### Load ExplainerDashboard from Configuration Source: https://github.com/oegedijk/explainerdashboard/blob/master/RELEASE_NOTES.md Use this class method to initialize a dashboard directly from a YAML configuration file. ```python ExplainerDashboard.from_config("dashboard.yaml") ``` -------------------------------- ### Custom Predictions Tab Example Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/index.md Provides an example of a custom tab for displaying prediction-related information. This allows for tailored views of prediction data within the dashboard. ```python from explainerdashboard.custom import ExplainerComponent from dash import html class CustomPredictionsTab(ExplainerComponent): def __init__(self, name, explainer, **kwargs): super().__init__(name=name, explainer=explainer, **kwargs) def _layout(self): return html.Div([ html.H3("Custom Prediction Details"), html.P(f"Number of predictions: {len(self.explainer.X)}") ]) ``` -------------------------------- ### Gunicorn Start Command for Fly.io Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/deployment.md Specifies the command to start the web application using gunicorn. Ensure the port matches the internal port configured during `fly launch`. ```bash web: gunicorn dashboard:app --bind 0.0.0.0:${PORT:-8080} ``` -------------------------------- ### Deploying to Fly.io Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/index.md Instructions and considerations for deploying an ExplainerDashboard application to Fly.io. This typically involves creating a `fly.toml` configuration file and building a Docker image. ```toml [render] # ... other configurations [http_service] internal_port = 8080 force_https = true [http_service.concurrency] max_per_server = 50 soft_limit = 50 hard_limit = 100 [[services.ports]] port = "80" handlers = ["http"] [[services.ports]] port = "443" handlers = ["http"] ``` -------------------------------- ### GET get_permutation_importances_df Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/explainers.md Retrieves a dataframe containing features ordered by their permutation importance. ```APIDOC ## GET get_permutation_importances_df ### Description Returns a dataframe with features ordered by permutation importance. ### Parameters #### Query Parameters - **topx** (int) - Optional - Only return topx most important features - **cutoff** (float) - Optional - Only return features with importance of at least cutoff - **pos_label** (any) - Optional - Positive label for classification ### Response #### Success Response (200) - **importance_df** (pd.DataFrame) - Dataframe containing permutation importances ``` -------------------------------- ### Run a RegressionExplainer dashboard Source: https://github.com/oegedijk/explainerdashboard/blob/master/README.md Example for regression models, including setting target units. ```python X_train, y_train, X_test, y_test = titanic_fare() model = RandomForestRegressor().fit(X_train, y_train) explainer = RegressionExplainer(model, X_test, y_test, cats=['Deck', 'Embarked', 'Sex'], descriptions=feature_descriptions, units = "$", # defaults to "" ) ExplainerDashboard(explainer).run() ``` -------------------------------- ### Create Basic ExplainerDashboard Source: https://context7.com/oegedijk/explainerdashboard/llms.txt Launch a full interactive dashboard with default tabs for model explanation. Configure which tabs to display and run the dashboard on a specified port. ```python from explainerdashboard import ClassifierExplainer, ExplainerDashboard from sklearn.ensemble import RandomForestClassifier from explainerdashboard.datasets import titanic_survive # Prepare data and model X_train, y_train, X_test, y_test = titanic_survive() model = RandomForestClassifier(n_estimators=50, max_depth=5).fit(X_train, y_train) # Create explainer explainer = ClassifierExplainer(model, X_test, y_test) # Create and run dashboard with all default tabs dashboard = ExplainerDashboard( explainer, title="Titanic Survival Classifier", description="Explains passenger survival predictions", # Control which tabs to show importances=True, # Feature importances tab model_summary=True, # Model performance metrics tab contributions=True, # Individual predictions tab whatif=True, # What-if analysis tab shap_dependence=True, # SHAP dependence plots tab shap_interaction=False, # Disable slow interaction tab decision_trees=True # Decision trees visualization ) # Run on specified port dashboard.run(port=8050) ``` -------------------------------- ### GET get_shap_values_df Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/explainers.md Calculates and returns SHAP values for the model using the shap library. ```APIDOC ## GET get_shap_values_df ### Description Calculates SHAP values using the shap library. ### Parameters #### Query Parameters - **pos_label** (any) - Optional - Positive label for classification ### Response #### Success Response (200) - **shap_values** (pd.DataFrame) - SHAP values calculated for the model ``` -------------------------------- ### View Server Output Source: https://github.com/oegedijk/explainerdashboard/blob/master/notebooks/custom_examples.ipynb Expected console output when the Dash application starts successfully. ```text Output: Dash app running on http://127.0.0.1:8050/ ``` -------------------------------- ### Initialize RandomForest Explainer Source: https://github.com/oegedijk/explainerdashboard/blob/master/notebooks/explainer_examples.ipynb Sets up a RandomForestClassifier and initializes the corresponding explainer. ```python from sklearn.ensemble import RandomForestClassifier from explainerdashboard.datasets import ( titanic_survive, titanic_names, feature_descriptions, ) X_train, y_train, X_test, y_test = titanic_survive() train_names, test_names = titanic_names() model = RandomForestClassifier(n_estimators=50, max_depth=5) model.fit(X_train, y_train) explainer = ClassifierExplainer( model, X_test, y_test, cats=["Sex", "Deck", "Embarked"], idxs=test_names ) ``` -------------------------------- ### Save and Load Explainer Source: https://context7.com/oegedijk/explainerdashboard/llms.txt Demonstrates how to save an explainer object to disk using 'dump' and load it back using 'from_file' for faster dashboard startup. Supports multiple file formats. ```python from explainerdashboard import ClassifierExplainer, ExplainerDashboard from sklearn.ensemble import RandomForestClassifier from explainerdashboard.datasets import titanic_survive # Create and train model X_train, y_train, X_test, y_test = titanic_survive() model = RandomForestClassifier(n_estimators=50).fit(X_train, y_train) # Create explainer and calculate all properties (can take time) explainer = ClassifierExplainer(model, X_test, y_test) # Pre-calculate expensive properties explainer.calculate_properties() # Calculate all # Or calculate specific properties: # explainer.shap_values() # explainer.permutation_importances() # explainer.shap_interaction_values() # Save to disk (uses joblib by default) explainer.dump('explainer.joblib') # Load from disk - much faster than recalculating loaded_explainer = ClassifierExplainer.from_file('explainer.joblib') # Alternative formats explainer.dump('explainer.pkl') # Pickle format explainer.dump('explainer.dill') # Dill format (for complex objects) # Create dashboard from loaded explainer dashboard = ExplainerDashboard(loaded_explainer, title="Loaded Dashboard") dashboard.run() ``` -------------------------------- ### Run ExplainerDashboard on Specific Port Source: https://github.com/oegedijk/explainerdashboard/blob/master/notebooks/dashboard_examples.ipynb Launch the ExplainerDashboard on a specified port, for example, port 8051. ```python db.run(8051) ``` -------------------------------- ### ExplainerDashboard Initialization and Usage Source: https://github.com/oegedijk/explainerdashboard/blob/master/notebooks/dashboard_examples.ipynb Demonstrates how to initialize and run the ExplainerDashboard for classification tasks, including customizing components. ```APIDOC ## ExplainerDashboard Initialization and Usage ### Description This section details the initialization of the `ExplainerDashboard` class for classification models. It shows how to enable a simple mode that displays a predefined set of components and how to customize specific components. ### Method `ExplainerDashboard(explainer, simple=False, classifier_custom_component=None, ...)` ### Endpoint N/A (Class initialization) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Basic initialization for simple mode db = ExplainerDashboard(explainer, simple=True) db.run() # With a customized classification component db = ExplainerDashboard(explainer, simple=True, classifier_custom_component="precision_graph") db.run() ``` ### Response #### Success Response (200) N/A (This is a class initialization and method call, not an HTTP endpoint) #### Response Example N/A ``` -------------------------------- ### Get Decision Path Dataframe Source: https://github.com/oegedijk/explainerdashboard/blob/master/notebooks/explainer_examples.ipynb Retrieves the decision path details for a specific tree and instance. ```python explainer.get_decisionpath_df(tree_idx=20, index=name) ``` -------------------------------- ### Run Custom Dashboard from YAML Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/cli.md Launch a custom explainer dashboard using a previously created YAML configuration file. ```bash $ explainerdashboard run dashboard.yaml ``` -------------------------------- ### Initialize ExplainerDashboard Source: https://github.com/oegedijk/explainerdashboard/blob/master/notebooks/dashboard_examples.ipynb Create an ExplainerDashboard instance from an explainer object. This pre-calculates necessary metrics for the dashboard. ```python db = ExplainerDashboard(explainer) ``` -------------------------------- ### Run Dashboard with Waitress Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/deployment.md Start the waitress server to host your dashboard, binding to port 8050. ```bash $ waitress-serve --port=8050 dashboard:app ``` -------------------------------- ### Configure ClassifierExplainer with LogisticRegression Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/explainers.md Example of initializing a ClassifierExplainer with specific background data and model output settings. ```python from sklearn.linear_model import LogisticRegression model = LogisticRegression() model.fit(X_train, y_train) explainer = ClassifierExplainer(model, X_test, y_test, shap='linear', X_background=X_train, model_output='logodds') ExplainerDashboard(explainer).run() ``` -------------------------------- ### ExplainerHub.from_config Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/hub.md Instantiate an ExplainerHub based on a configuration file or dictionary. ```APIDOC ## classmethod from_config ### Description Instantiate an ExplainerHub based on a config file or dictionary. ### Parameters - **config** (Union[dict, str, Path]) - Required - Either a dict or a .yaml config file to load. - **update_params** (dict) - Optional - Additional kwargs to override stored settings. ### Response - **Returns** (ExplainerHub) - New instance of ExplainerHub according to the config. ``` -------------------------------- ### ExplainerHub Initialization Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/hub.md Parameters for configuring and initializing an ExplainerHub instance. ```APIDOC ## ExplainerHub Initialization ### Description Initializes an ExplainerHub to manage multiple ExplainerDashboard instances. ### Parameters - **dashboards** (List[ExplainerDashboard]) - Required - List of ExplainerDashboard to include in ExplainerHub. - **title** (str) - Optional - Title to display. Defaults to “ExplainerHub”. - **description** (str) - Optional - Short description of ExplainerHub. - **masonry** (bool) - Optional - Lay out dashboard cards in fluid bootstrap masonry responsive style. Defaults to False. - **n_dashboard_cols** (int) - Optional - Organize cards in rows and columns. Defaults to 3 columns. - **users_file** (Path) - Optional - A .yaml or .json file used to store user and (hashed) password data. Defaults to ‘users.yaml’. - **user_json** (Path) - Optional - Deprecated. A .json file used to store user and (hashed) password data. - **logins** (List[List[str, str]]) - Optional - List of [‘login’, ‘password’] pairs. - **db_users** (dict) - Optional - Dictionary limiting access to certain dashboards to a subset of users. - **dbs_open_by_default** (bool) - Optional - Only force logins for dashboard with defined db_users. Defaults to False. - **port** (int) - Optional - Port to run hub on. Defaults to 8050. - **min_height** (int) - Optional - Defaults to 3000 pixels. - **secret_key** (str) - Required - Flask secret key to pass to dashboard in order to persist logins. - **no_index** (bool) - Optional - Do not add the “/” route, but only mount the dashboards. - **bootstrap** (str) - Optional - URL with custom bootstrap css. - **fluid** (bool) - Optional - Let the bootstrap container fill the entire width of the browser. Defaults to True. - **base_route** (str) - Optional - Base route for dashboard. Defaults to “dashboards”. - **index_to_base_route** (bool) - Optional - Dispatches Hub to “/base_route/index” instead of the default “/”. - **static_to_base_route** (bool) - Optional - Dispatches Hub to “/base_route/static” instead of the default “/static”. - **max_dashboards** (int) - Optional - Max number of dashboards in the hub. - **add_dashboard_route** (bool) - Optional - Open a route /add_dashboard and /remove_dashboard. - **add_dashboard_pattern** (str) - Optional - A str pattern with curly brackets for dashboard file location. ``` -------------------------------- ### Get Decision Path Summary Source: https://github.com/oegedijk/explainerdashboard/blob/master/notebooks/explainer_examples.ipynb Retrieves a summary of the decision path adjustments for a specific tree and instance. ```python explainer.get_decisionpath_summary_df(tree_idx=5, index=name) ``` -------------------------------- ### Constructor: ExplainerDashboard Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/dashboards.md Initializes a new ExplainerDashboard instance to visualize model explanations. ```APIDOC ## Constructor: ExplainerDashboard ### Description Creates an explainerdashboard out of an Explainer object. The dashboard can be configured as a single-page or multi-tab layout with various display modes. ### Parameters #### Request Body - **explainer** (BaseExplainer) - Required - The explainer object to visualize. - **tabs** (ExplainerComponent | List[ExplainerComponent]) - Optional - Single component or list of components to display. - **title** (str) - Optional - Title of the dashboard, defaults to 'Model Explainer'. - **mode** (str) - Optional - Type of dash server to start: 'dash', 'inline', 'jupyterlab', or 'external'. - **fluid** (bool) - Optional - Whether to stretch the layout to available space, defaults to True. - **width** (int) - Optional - Width of notebook output cell in pixels, defaults to 1000. - **height** (int) - Optional - Height of notebook output cell in pixels, defaults to 800. - **bootstrap** (str) - Optional - Link to bootstrap URL. - **external_stylesheets** (List[str]) - Optional - Additional external stylesheets. ``` -------------------------------- ### Construct and run a basic ClassifierExplainer Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/index.md Initialize an explainer object with a model and test data, then launch the dashboard. ```python from explainerdashboard import ClassifierExplainer, ExplainerDashboard explainer = ClassifierExplainer(model, X_test, y_test) ``` ```python ExplainerDashboard(explainer).run() ``` -------------------------------- ### Build Explainer from Configuration (CLI) Source: https://context7.com/oegedijk/explainerdashboard/llms.txt Build explainers from YAML configuration files, useful for CI/CD pipelines. Can specify both explainer and dashboard configurations. ```bash # Build explainer from configuration (for CI/CD) explainerdashboard build explainer.yaml ``` ```bash # Build with specific dashboard configuration explainerdashboard build explainer.yaml dashboard.yaml ``` -------------------------------- ### Persist and restore hub configuration Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/hub.md Saves the current hub setup to a YAML file and restores it later. ```python hub.to_yaml('hub.yaml') ``` ```python hub2 = ExplainerHub.from_config('hub.yaml') ``` -------------------------------- ### Initialize and Run ExplainerDashboard Source: https://github.com/oegedijk/explainerdashboard/blob/master/notebooks/custom_examples.ipynb Use this snippet to initialize an ExplainerDashboard with a given explainer and custom dashboard class. The bootstrap theme and header visibility can be configured. The dashboard will run on http://localhost:8050. ```python from explainerdashboard import ExplainerDashboard ExplainerDashboard( explainer, CustomDashboard, boostrap=dbc.themes.FLATLY, hide_header=True ).run() ``` -------------------------------- ### Get Base Explainer Metrics Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/explainers.md Retrieves a dictionary of performance metrics for the explainer. This method is implemented by both ClassifierExplainer and RegressionExplainer. ```python metrics() ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/oegedijk/explainerdashboard/blob/master/CONTRIBUTING.md Initialize a new Python virtual environment to isolate project dependencies. ```bash $ python -m venv venv $ source venv/bin/activate ``` -------------------------------- ### Server Request Logs Source: https://github.com/oegedijk/explainerdashboard/blob/master/notebooks/simplified_classifier_dashboard_example.ipynb Sample output showing HTTP GET and POST requests handled by the ExplainerDashboard server. ```text 192.168.1.21 - - [07/May/2021 15:47:12] "GET /_dash-component-suites/dash_renderer/react-dom@16.v1_9_1m1618962237.14.0.min.js HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:12] "GET /_dash-component-suites/dash_renderer/polyfill@7.v1_9_1m1618962237.8.7.min.js HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:12] "GET /_dash-component-suites/dash_renderer/prop-types@15.v1_9_1m1618962237.7.2.min.js HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:12] "GET /_dash-component-suites/dash_core_components/dash_core_components.v1_16_0m1618962238.min.js HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:12] "GET /_dash-component-suites/dash_core_components/dash_core_components-shared.v1_16_0m1618962238.js HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:12] "GET /_dash-component-suites/dash_table/bundle.v4_11_3m1618962241.js HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:12] "GET /_dash-component-suites/dash_bootstrap_components/_components/dash_bootstrap_components.v0_12_0m1618962292.min.js HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:12] "GET /_dash-component-suites/dash_html_components/dash_html_components.v1_1_3m1618962240.min.js HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:12] "GET /_dash-component-suites/dash_renderer/dash_renderer.v1_9_1m1618962237.min.js HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:13] "GET /_dash-layout HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:13] "GET /_dash-dependencies HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:13] "GET /assets/favicon.ico?m=1620419845.4037383 HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:14] "GET /_dash-component-suites/dash_core_components/async-dropdown.v1_16_0m1617903285.js HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:14] "GET /_dash-component-suites/dash_core_components/async-graph.v1_16_0m1617903285.js HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:14] "GET /_dash-component-suites/dash_core_components/async-slider.v1_16_0m1617903285.js HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:14] "GET /_dash-component-suites/dash_core_components/async-plotlyjs.v1_16_0m1617903285.js HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:14] "POST /_dash-update-component HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:14] "POST /_dash-update-component HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:14] "POST /_dash-update-component HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:14] "POST /_dash-update-component HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:14] "POST /_dash-update-component HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:14] "POST /_dash-update-component HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:14] "POST /_dash-update-component HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:14] "POST /_dash-update-component HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:14] "POST /_dash-update-component HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:14] "POST /_dash-update-component HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:14] "POST /_dash-update-component HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:14] "POST /_dash-update-component HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:15] "POST /_dash-update-component HTTP/1.1" 204 - 192.168.1.21 - - [07/May/2021 15:47:15] "POST /_dash-update-component HTTP/1.1" 204 - 192.168.1.21 - - [07/May/2021 15:47:15] "POST /_dash-update-component HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:15] "POST /_dash-update-component HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:15] "POST /_dash-update-component HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:15] "POST /_dash-update-component HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:15] "POST /_dash-update-component HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:16] "POST /_dash-update-component HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:16] "POST /_dash-update-component HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:16] "POST /_dash-update-component HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:16] "POST /_dash-update-component HTTP/1.1" 200 - 192.168.1.21 - - [07/May/2021 15:47:16] "POST /_dash-update-component HTTP/1.1" 200 - ``` -------------------------------- ### Run ExplainerDashboard from CLI Source: https://context7.com/oegedijk/explainerdashboard/llms.txt Use the command-line interface to run dashboards from explainer files or YAML configurations. Options include specifying ports, disabling browser launch, and running on AWS SageMaker. ```bash # Run dashboard from explainer file explainerdashboard run explainer.joblib ``` ```bash # Run dashboard from YAML configuration explainerdashboard run dashboard.yaml ``` ```bash # Run with specific port and no browser launch explainerdashboard run dashboard.yaml --port 8051 --no-browser ``` ```bash # Run on AWS SageMaker with proxy settings explainerdashboard run dashboard.yaml --sagemaker ``` -------------------------------- ### Customize ExplainerDashboard Classification Component Source: https://github.com/oegedijk/explainerdashboard/blob/master/notebooks/dashboard_examples.ipynb Customize the classification component by passing a string to `classifier_custom_component`. For example, use 'precision_graph' for the PrecisionComponent. ```python db = ExplainerDashboard( explainer, simple=True, classifier_custom_component="precision_graph" ) db.run() ``` -------------------------------- ### Configure Dashboard Tabs Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/dashboards.md Example of mixing component classes, string identifiers, and custom tab instances for the tabs parameter. ```python tabs=[ImportancesTab, “contributions”, custom_tab] ``` -------------------------------- ### ExplainerDashboard.from_config Source: https://github.com/oegedijk/explainerdashboard/blob/master/docs/source/cli.md Loads a dashboard from a configuration YAML file or directly from an explainer file. ```APIDOC ## ExplainerDashboard.from_config ### Description Loading a dashboard from a configuration .yaml file. You can either pass both an explainer and a yaml file generated with ExplainerDashboard.to_yaml("dashboard.yaml"), or just the .yaml if the explainerfile was specified in to_yaml, or load the explainerfile separately. ### Method Class Method ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Example 1: Passing explainer and yaml file db = ExplainerDashboard.from_config(explainer, "dashboard.yaml") # Example 2: Passing only yaml file (if explainerfile was specified in to_yaml) db = ExplainerDashboard.from_config("dashboard.yaml") # Example 3: Passing explainer file and yaml file separately db = ExplainerDashboard.from_config("explainer.joblib", "dashboard.yaml") # Example 4: Overriding parameters db = ExplainerDashboard.from_config("dashboard.yaml", update_params={"title": "My Custom Dashboard"}) ``` ### Response #### Success Response (200) An instance of ExplainerDashboard. #### Response Example ```python # Example of a returned ExplainerDashboard instance (conceptual) print(db) ``` ``` -------------------------------- ### Train Model and Build Explainer Source: https://github.com/oegedijk/explainerdashboard/blob/master/notebooks/custom_examples.ipynb Prepare data, train a Random Forest model, and initialize the ClassifierExplainer. ```python X_train, y_train, X_test, y_test = titanic_survive() model = RandomForestClassifier(n_estimators=50, max_depth=15).fit(X_train, y_train) explainer = ClassifierExplainer( model, X_test, y_test, cats=["Sex", "Deck", "Embarked"], descriptions=feature_descriptions, labels=["Not survived", "Survived"], ) explainer.plot_contributions(0) ```