{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Use GPU to speedup SHAP value computation\n\nDemonstrates using GPU acceleration to compute SHAP values for feature importance.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from urllib.error import HTTPError\n\nimport shap\nfrom sklearn.datasets import fetch_california_housing, make_regression\n\nimport xgboost as xgb\n\n# Fetch dataset using sklearn\ntry:\n    _data = fetch_california_housing(return_X_y=True)\n    X = _data.data\n    y = _data.target\n    feature_names = _data.feature_names\n    print(_data.DESCR)\nexcept HTTPError:\n    # Use a synthetic dataset instead if we couldn't\n    X, y = make_regression(n_samples=20640, n_features=8, random_state=1234)\n    feature_names = [f\"f{i}\" for i in range(8)]\n\nnum_round = 500\n\nparam = {\n    \"eta\": 0.05,\n    \"max_depth\": 10,\n    \"tree_method\": \"hist\",\n    \"device\": \"cuda\",\n}\n\n# GPU accelerated training\ndtrain = xgb.DMatrix(X, label=y, feature_names=feature_names)\nmodel = xgb.train(param, dtrain, num_round)\n\n# Compute shap values using GPU with xgboost\nmodel.set_param({\"device\": \"cuda\"})\nshap_values = model.predict(dtrain, pred_contribs=True)\n\n# Compute shap interaction values using GPU\nshap_interaction_values = model.predict(dtrain, pred_interactions=True)\n\n\n# shap will call the GPU accelerated version as long as the device parameter is set to\n# \"cuda\"\nexplainer = shap.TreeExplainer(model)\nshap_values = explainer.shap_values(X)\n\n# visualize the first prediction's explanation\nshap.force_plot(\n    explainer.expected_value,\n    shap_values[0, :],\n    X[0, :],\n    feature_names=feature_names,\n    matplotlib=True,\n)\n\n# Show a summary of feature importance\nshap.summary_plot(shap_values, X, plot_type=\"bar\", feature_names=feature_names)"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.10.17"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}