trepan-demo-checkpoint.ipynb 31.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Using Trepan: a demonstration\n",
    "\n",
    "By: Yuriy Sverchkov\n",
    "\n",
    "Assistant Scientist\n",
    "\n",
    "Department of Biostatistics and Medical Informatics\n",
    "\n",
    "University of Wisconsin - Madison, USA\n",
    "\n",
    "## Trepan\n",
    "\n",
    "[M. Craven and J. Shalvik. 1995. Extracting tree-structured representations of trained networks. In Proceedings of the 8th International Conference on Neural Information Processing 1995](https://dl.acm.org/doi/10.5555/2998828.2998832)\n",
    "\n",
    "Trepan is one of the first explanation-by-model-translation methods for Neural Networks.\n",
    "Model translation is an approach to model explanation in which an uninterpretable black-box model is translated into an interpretable model (in this case a decision tree) that aims at having high fidelity to the black-box model, that is, make similar prediction to it.\n",
    "\n",
    "In this notebook we will use a modern implementation in the [`generalizedtrees`](https://github.com/Craven-Biostat-Lab/generalizedtrees) package to run Trepan on one of the original datasets used in the paper. `generalizedtrees` is under development with major changes from version to version. It is a project that attempts to bring together many different variants of tree learning together into a single framework.\n",
    "\n",
    "For this notebook we will use `generalizedtrees` version 1.1.0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: generalizedtrees==1.1.0 in /Users/sees/.virtualenvs/trepan-demo/lib/python3.8/site-packages (1.1.0)\n",
      "Requirement already satisfied: scipy>=1.5.2 in /Users/sees/.virtualenvs/trepan-demo/lib/python3.8/site-packages (from generalizedtrees==1.1.0) (1.6.0)\n",
      "Requirement already satisfied: pandas>=1.1.0 in /Users/sees/.virtualenvs/trepan-demo/lib/python3.8/site-packages (from generalizedtrees==1.1.0) (1.2.2)\n",
      "Requirement already satisfied: scikit-learn>=0.23.2 in /Users/sees/.virtualenvs/trepan-demo/lib/python3.8/site-packages (from generalizedtrees==1.1.0) (0.24.1)\n",
      "Requirement already satisfied: numpy>=1.19.1 in /Users/sees/.virtualenvs/trepan-demo/lib/python3.8/site-packages (from generalizedtrees==1.1.0) (1.20.1)\n",
      "Requirement already satisfied: python-dateutil>=2.7.3 in /Users/sees/.virtualenvs/trepan-demo/lib/python3.8/site-packages (from pandas>=1.1.0->generalizedtrees==1.1.0) (2.8.1)\n",
      "Requirement already satisfied: pytz>=2017.3 in /Users/sees/.virtualenvs/trepan-demo/lib/python3.8/site-packages (from pandas>=1.1.0->generalizedtrees==1.1.0) (2021.1)\n",
      "Requirement already satisfied: threadpoolctl>=2.0.0 in /Users/sees/.virtualenvs/trepan-demo/lib/python3.8/site-packages (from scikit-learn>=0.23.2->generalizedtrees==1.1.0) (2.1.0)\n",
      "Requirement already satisfied: joblib>=0.11 in /Users/sees/.virtualenvs/trepan-demo/lib/python3.8/site-packages (from scikit-learn>=0.23.2->generalizedtrees==1.1.0) (1.0.1)\n",
      "Requirement already satisfied: six>=1.5 in /Users/sees/.virtualenvs/trepan-demo/lib/python3.8/site-packages (from python-dateutil>=2.7.3->pandas>=1.1.0->generalizedtrees==1.1.0) (1.15.0)\n",
      "\u001b[33mWARNING: You are using pip version 20.2.3; however, version 21.0.1 is available.\n",
      "You should consider upgrading via the '/Users/sees/.virtualenvs/trepan-demo/bin/python -m pip install --upgrade pip' command.\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "import sys\n",
    "!{sys.executable} -m pip install generalizedtrees==1.1.0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Data\n",
    "\n",
    "We will use the Cleveland Heart Disease dataset, available from the UCI repository: http://archive.ics.uci.edu/ml/datasets/Heart+Disease.\n",
    "The file we load here is specifically http://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/cleve.mod."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "from sklearn.preprocessing import OneHotEncoder, LabelEncoder\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "np_rng = np.random.default_rng(8372234)\n",
    "sk_rng = np.random.RandomState(3957458)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>age</th>\n",
       "      <th>sex</th>\n",
       "      <th>chest pain type</th>\n",
       "      <th>resting bp</th>\n",
       "      <th>cholesterol</th>\n",
       "      <th>fasting blood sugar &lt; 120</th>\n",
       "      <th>resting ecg</th>\n",
       "      <th>max heart rate</th>\n",
       "      <th>exercise induced angina</th>\n",
       "      <th>oldpeak</th>\n",
       "      <th>slope</th>\n",
       "      <th>number of vessels colored</th>\n",
       "      <th>thal</th>\n",
       "      <th>class</th>\n",
       "      <th>stage</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>63.0</td>\n",
       "      <td>male</td>\n",
       "      <td>angina</td>\n",
       "      <td>145.0</td>\n",
       "      <td>233.0</td>\n",
       "      <td>True</td>\n",
       "      <td>hyp</td>\n",
       "      <td>150.0</td>\n",
       "      <td>False</td>\n",
       "      <td>2.3</td>\n",
       "      <td>down</td>\n",
       "      <td>0.0</td>\n",
       "      <td>fix</td>\n",
       "      <td>buff</td>\n",
       "      <td>H</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>67.0</td>\n",
       "      <td>male</td>\n",
       "      <td>asympt</td>\n",
       "      <td>160.0</td>\n",
       "      <td>286.0</td>\n",
       "      <td>False</td>\n",
       "      <td>hyp</td>\n",
       "      <td>108.0</td>\n",
       "      <td>True</td>\n",
       "      <td>1.5</td>\n",
       "      <td>flat</td>\n",
       "      <td>3.0</td>\n",
       "      <td>norm</td>\n",
       "      <td>sick</td>\n",
       "      <td>S2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>67.0</td>\n",
       "      <td>male</td>\n",
       "      <td>asympt</td>\n",
       "      <td>120.0</td>\n",
       "      <td>229.0</td>\n",
       "      <td>False</td>\n",
       "      <td>hyp</td>\n",
       "      <td>129.0</td>\n",
       "      <td>True</td>\n",
       "      <td>2.6</td>\n",
       "      <td>flat</td>\n",
       "      <td>2.0</td>\n",
       "      <td>rev</td>\n",
       "      <td>sick</td>\n",
       "      <td>S1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>37.0</td>\n",
       "      <td>male</td>\n",
       "      <td>notang</td>\n",
       "      <td>130.0</td>\n",
       "      <td>250.0</td>\n",
       "      <td>False</td>\n",
       "      <td>norm</td>\n",
       "      <td>187.0</td>\n",
       "      <td>False</td>\n",
       "      <td>3.5</td>\n",
       "      <td>down</td>\n",
       "      <td>0.0</td>\n",
       "      <td>norm</td>\n",
       "      <td>buff</td>\n",
       "      <td>H</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>41.0</td>\n",
       "      <td>fem</td>\n",
       "      <td>abnang</td>\n",
       "      <td>130.0</td>\n",
       "      <td>204.0</td>\n",
       "      <td>False</td>\n",
       "      <td>hyp</td>\n",
       "      <td>172.0</td>\n",
       "      <td>False</td>\n",
       "      <td>1.4</td>\n",
       "      <td>up</td>\n",
       "      <td>0.0</td>\n",
       "      <td>norm</td>\n",
       "      <td>buff</td>\n",
       "      <td>H</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>298</th>\n",
       "      <td>48.0</td>\n",
       "      <td>male</td>\n",
       "      <td>notang</td>\n",
       "      <td>124.0</td>\n",
       "      <td>255.0</td>\n",
       "      <td>True</td>\n",
       "      <td>norm</td>\n",
       "      <td>175.0</td>\n",
       "      <td>False</td>\n",
       "      <td>0.0</td>\n",
       "      <td>up</td>\n",
       "      <td>2.0</td>\n",
       "      <td>norm</td>\n",
       "      <td>buff</td>\n",
       "      <td>H</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>299</th>\n",
       "      <td>57.0</td>\n",
       "      <td>male</td>\n",
       "      <td>asympt</td>\n",
       "      <td>132.0</td>\n",
       "      <td>207.0</td>\n",
       "      <td>False</td>\n",
       "      <td>norm</td>\n",
       "      <td>168.0</td>\n",
       "      <td>True</td>\n",
       "      <td>0.0</td>\n",
       "      <td>up</td>\n",
       "      <td>0.0</td>\n",
       "      <td>rev</td>\n",
       "      <td>buff</td>\n",
       "      <td>H</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>300</th>\n",
       "      <td>49.0</td>\n",
       "      <td>male</td>\n",
       "      <td>notang</td>\n",
       "      <td>118.0</td>\n",
       "      <td>149.0</td>\n",
       "      <td>False</td>\n",
       "      <td>hyp</td>\n",
       "      <td>126.0</td>\n",
       "      <td>False</td>\n",
       "      <td>0.8</td>\n",
       "      <td>up</td>\n",
       "      <td>3.0</td>\n",
       "      <td>norm</td>\n",
       "      <td>sick</td>\n",
       "      <td>S1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>301</th>\n",
       "      <td>74.0</td>\n",
       "      <td>fem</td>\n",
       "      <td>abnang</td>\n",
       "      <td>120.0</td>\n",
       "      <td>269.0</td>\n",
       "      <td>False</td>\n",
       "      <td>hyp</td>\n",
       "      <td>121.0</td>\n",
       "      <td>True</td>\n",
       "      <td>0.2</td>\n",
       "      <td>up</td>\n",
       "      <td>1.0</td>\n",
       "      <td>norm</td>\n",
       "      <td>buff</td>\n",
       "      <td>H</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>302</th>\n",
       "      <td>54.0</td>\n",
       "      <td>fem</td>\n",
       "      <td>notang</td>\n",
       "      <td>160.0</td>\n",
       "      <td>201.0</td>\n",
       "      <td>False</td>\n",
       "      <td>norm</td>\n",
       "      <td>163.0</td>\n",
       "      <td>False</td>\n",
       "      <td>0.0</td>\n",
       "      <td>up</td>\n",
       "      <td>1.0</td>\n",
       "      <td>norm</td>\n",
       "      <td>buff</td>\n",
       "      <td>H</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>296 rows × 15 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "      age   sex chest pain type  resting bp  cholesterol  \\\n",
       "0    63.0  male          angina       145.0        233.0   \n",
       "1    67.0  male          asympt       160.0        286.0   \n",
       "2    67.0  male          asympt       120.0        229.0   \n",
       "3    37.0  male          notang       130.0        250.0   \n",
       "4    41.0   fem          abnang       130.0        204.0   \n",
       "..    ...   ...             ...         ...          ...   \n",
       "298  48.0  male          notang       124.0        255.0   \n",
       "299  57.0  male          asympt       132.0        207.0   \n",
       "300  49.0  male          notang       118.0        149.0   \n",
       "301  74.0   fem          abnang       120.0        269.0   \n",
       "302  54.0   fem          notang       160.0        201.0   \n",
       "\n",
       "     fasting blood sugar < 120 resting ecg  max heart rate  \\\n",
       "0                         True         hyp           150.0   \n",
       "1                        False         hyp           108.0   \n",
       "2                        False         hyp           129.0   \n",
       "3                        False        norm           187.0   \n",
       "4                        False         hyp           172.0   \n",
       "..                         ...         ...             ...   \n",
       "298                       True        norm           175.0   \n",
       "299                      False        norm           168.0   \n",
       "300                      False         hyp           126.0   \n",
       "301                      False         hyp           121.0   \n",
       "302                      False        norm           163.0   \n",
       "\n",
       "     exercise induced angina  oldpeak slope  number of vessels colored  thal  \\\n",
       "0                      False      2.3  down                        0.0   fix   \n",
       "1                       True      1.5  flat                        3.0  norm   \n",
       "2                       True      2.6  flat                        2.0   rev   \n",
       "3                      False      3.5  down                        0.0  norm   \n",
       "4                      False      1.4    up                        0.0  norm   \n",
       "..                       ...      ...   ...                        ...   ...   \n",
       "298                    False      0.0    up                        2.0  norm   \n",
       "299                     True      0.0    up                        0.0   rev   \n",
       "300                    False      0.8    up                        3.0  norm   \n",
       "301                     True      0.2    up                        1.0  norm   \n",
       "302                    False      0.0    up                        1.0  norm   \n",
       "\n",
       "    class stage  \n",
       "0    buff     H  \n",
       "1    sick    S2  \n",
       "2    sick    S1  \n",
       "3    buff     H  \n",
       "4    buff     H  \n",
       "..    ...   ...  \n",
       "298  buff     H  \n",
       "299  buff     H  \n",
       "300  sick    S1  \n",
       "301  buff     H  \n",
       "302  buff     H  \n",
       "\n",
       "[296 rows x 15 columns]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "full_data = pd.read_fwf(\n",
    "    'cleveland.txt',\n",
    "    skiprows=20,\n",
    "    names = [\n",
    "        'age', 'sex', 'chest pain type', 'resting bp', 'cholesterol', 'fasting blood sugar < 120', 'resting ecg',\n",
    "        'max heart rate', 'exercise induced angina', 'oldpeak', 'slope', 'number of vessels colored', 'thal', 'class', 'stage'\n",
    "    ],\n",
    "    true_values = ['true'],\n",
    "    false_values = ['fal'],\n",
    "    na_values = '?').dropna(axis=0)\n",
    "\n",
    "full_data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Since we will be using scikit-learn to learn our black-box model, we need to convert categorical variables to numeric vectors.\n",
    "We will also make a train-test split."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_df = full_data.drop(['class', 'stage'], axis=1)\n",
    "\n",
    "encoder = OneHotEncoder(drop = 'if_binary')\n",
    "lencoder = LabelEncoder()\n",
    "\n",
    "numeric_features = data_df.select_dtypes(include = 'number')\n",
    "categorical_features_df = data_df.select_dtypes(exclude = 'number')\n",
    "categorical_features = encoder.fit_transform(categorical_features_df).toarray()\n",
    "feature_names = np.append(numeric_features.columns, encoder.get_feature_names(categorical_features_df.columns))\n",
    "\n",
    "x = np.append(\n",
    "    numeric_features,\n",
    "    categorical_features,\n",
    "    axis = 1)\n",
    "\n",
    "y = lencoder.fit_transform(full_data['class'])\n",
    "\n",
    "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.1, random_state = sk_rng)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Our new feature set is below. Subsequently features will be referenced by their 0-index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Feature Name</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>age</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>resting bp</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>cholesterol</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>max heart rate</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>oldpeak</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>number of vessels colored</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>sex_male</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>chest pain type_abnang</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>chest pain type_angina</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>chest pain type_asympt</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>chest pain type_notang</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>fasting blood sugar &lt; 120_True</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>resting ecg_abn</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>resting ecg_hyp</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>14</th>\n",
       "      <td>resting ecg_norm</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>15</th>\n",
       "      <td>exercise induced angina_True</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>16</th>\n",
       "      <td>slope_down</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>17</th>\n",
       "      <td>slope_flat</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>18</th>\n",
       "      <td>slope_up</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>19</th>\n",
       "      <td>thal_fix</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>20</th>\n",
       "      <td>thal_norm</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>21</th>\n",
       "      <td>thal_rev</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                      Feature Name\n",
       "0                              age\n",
       "1                       resting bp\n",
       "2                      cholesterol\n",
       "3                   max heart rate\n",
       "4                          oldpeak\n",
       "5        number of vessels colored\n",
       "6                         sex_male\n",
       "7           chest pain type_abnang\n",
       "8           chest pain type_angina\n",
       "9           chest pain type_asympt\n",
       "10          chest pain type_notang\n",
       "11  fasting blood sugar < 120_True\n",
       "12                 resting ecg_abn\n",
       "13                 resting ecg_hyp\n",
       "14                resting ecg_norm\n",
       "15    exercise induced angina_True\n",
       "16                      slope_down\n",
       "17                      slope_flat\n",
       "18                        slope_up\n",
       "19                        thal_fix\n",
       "20                       thal_norm\n",
       "21                        thal_rev"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.DataFrame({'Feature Name': feature_names})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Black-box model\n",
    "\n",
    "Like in the paper, our black-box model will be a fully connected Neural Network with one hidden layer, and the size of the layer is determined by cross-validation within the training set."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Pipeline(steps=[('standardscaler', StandardScaler()),\n",
       "                ('mlpclassifier',\n",
       "                 MLPClassifier(alpha=1e-05, hidden_layer_sizes=(5,),\n",
       "                               random_state=RandomState(MT19937) at 0x13B59DA40,\n",
       "                               solver='lbfgs'))])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.model_selection import GridSearchCV\n",
    "from sklearn.neural_network import MLPClassifier\n",
    "from sklearn.pipeline import make_pipeline\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "model = GridSearchCV(\n",
    "    make_pipeline(StandardScaler(), MLPClassifier(solver='lbfgs', alpha=1e-5, random_state=sk_rng)),\n",
    "    param_grid = {'mlpclassifier__hidden_layer_sizes': [(5,), (10,), (20,), (40,)]},\n",
    "    refit = True\n",
    ")\n",
    "\n",
    "model.fit(x_train, y_train)\n",
    "\n",
    "model.best_estimator_"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Decision tree explanation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "from generalizedtrees.recipes import trepan\n",
    "from generalizedtrees.vis.vis import explanation_to_html\n",
    "from generalizedtrees.features import FeatureSpec"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We have a function that serves as a 'recipe' for Trepan in our `generalizedtrees` python package, this returns an object that can be fit to data and a model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "explanation = trepan(\n",
    "    m_of_n=False,\n",
    "    max_tree_size=10,\n",
    "    impurity='entropy',\n",
    "    rng = np_rng)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We learn the explanation from the black-box model using the `fit` method, which takes unlabeled data and the black-box model as input."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Assuming continuous features in the absence of feature specifications\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Time taken to learn explanation: 3.302284002304077 seconds\n"
     ]
    }
   ],
   "source": [
    "t0 = time.time()\n",
    "\n",
    "explanation.fit(x_train, model)\n",
    "\n",
    "t1 = time.time()\n",
    "\n",
    "print(f'Time taken to learn explanation: {t1-t0} seconds')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A console-friendly representation of the tree is available:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Test x[5] > 0.5\n",
      "+--Test x[5] > 1.5\n",
      "|  +--[0.49 0.51]\n",
      "|  +--[0.577 0.423]\n",
      "+--Test x[4] > 1.55\n",
      "   +--[0.539 0.461]\n",
      "   +--Test x[20] > 0.5\n",
      "      +--Test x[4] > 1.45\n",
      "      |  +--[0.561 0.439]\n",
      "      |  +--[0.699 0.301]\n",
      "      +--[0.601 0.399]\n"
     ]
    }
   ],
   "source": [
    "print(explanation.show_tree())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A graphical representation (as an HTML file) can be generated as well:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "explanation_to_html(explanation, 'explanation.html')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Open the generated html:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Click the follwing link: [explanation.html](explanation.html)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Performance comparison\n",
    "\n",
    "The resulting tree can itself be treated as a classifier, and we can check how this learned tree performs on test data, alongside the original black-box model for comparison."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "y_test_trepan = explanation.predict(x_test)\n",
    "y_test_model = model.predict(x_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Trepan:\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "        buff       0.71      0.94      0.81        16\n",
      "        sick       0.89      0.57      0.70        14\n",
      "\n",
      "    accuracy                           0.77        30\n",
      "   macro avg       0.80      0.75      0.75        30\n",
      "weighted avg       0.80      0.77      0.76        30\n",
      "\n",
      "Black Box:\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "        buff       0.79      0.94      0.86        16\n",
      "        sick       0.91      0.71      0.80        14\n",
      "\n",
      "    accuracy                           0.83        30\n",
      "   macro avg       0.85      0.83      0.83        30\n",
      "weighted avg       0.85      0.83      0.83        30\n",
      "\n"
     ]
    }
   ],
   "source": [
    "from sklearn.metrics import classification_report\n",
    "\n",
    "print('Trepan:')\n",
    "print(classification_report(y_test, y_test_trepan, target_names=lencoder.classes_))\n",
    "\n",
    "print('Black Box:')\n",
    "print(classification_report(y_test, y_test_model, target_names=lencoder.classes_))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "Another metric of interest for explanation methods specifically is *fidelity*, which measures how well the explanation's predictions match the black-box predictions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training set fidelity\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "        buff       0.65      0.93      0.77       151\n",
      "        sick       0.80      0.34      0.48       115\n",
      "\n",
      "    accuracy                           0.68       266\n",
      "   macro avg       0.72      0.64      0.62       266\n",
      "weighted avg       0.71      0.68      0.64       266\n",
      "\n",
      "Test set fidelity\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "        buff       0.81      0.89      0.85        19\n",
      "        sick       0.78      0.64      0.70        11\n",
      "\n",
      "    accuracy                           0.80        30\n",
      "   macro avg       0.79      0.77      0.78        30\n",
      "weighted avg       0.80      0.80      0.80        30\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print('Training set fidelity')\n",
    "print(classification_report(model.predict(x_train), explanation.predict(x_train), target_names=lencoder.classes_))\n",
    "\n",
    "print('Test set fidelity')\n",
    "print(classification_report(y_test_model, y_test_trepan, target_names=lencoder.classes_))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Remarks\n",
    "\n",
    "There are some differences between the experiment presented here and the experiment in the paper. The version of Trepan we ran here did not use m-of-n splits at nodes (the search for splits becomes very slow if we enable it), we used a different number for the minimum samples required at each node (1000), and we used a simpler rejection-based sampling scheme for generating synthetic samples. The details of the neural network learning algorithm are also different.\n",
    "\n",
    "This notebook is available [in a gist](https://gist.github.com/sverchkov/c87b301db1b88e0f4cc8bb7d77b889b9).\n",
    "\n",
    "For issues/questions about the `generalizedtrees` package contact us through https://github.com/Craven-Biostat-Lab/generalizedtrees"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}