├── .github
├── CODEOWNERS
└── workflows
│ └── test.yml
├── .gitignore
├── LICENSE
├── README.md
├── docs
├── Quick feature selection through regression on Shapley values.ipynb
├── example.py
├── index.md
└── paper
│ ├── benchmark.py
│ └── shapley_select_paper_experiment.ipynb
├── mkdocs.yml
├── requirements.txt
├── setup.py
├── shap_select
├── __init__.py
└── select.py
└── tests
├── __init__.py
├── test_regression.py
├── test_shap_feature_generation.py
└── test_significance_calculation.py
/.github/CODEOWNERS:
--------------------------------------------------------------------------------
1 | * @transferwise/data-scientists
2 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: Run tests on merge
2 |
3 | on:
4 | pull_request:
5 | branches:
6 | - main
7 |
8 | jobs:
9 | test:
10 | runs-on: ubuntu-latest
11 |
12 | steps:
13 | # Checkout the repository code
14 | - name: Checkout code
15 | uses: actions/checkout@v3
16 |
17 | # Set up Python environment
18 | - name: Set up Python
19 | uses: actions/setup-python@v4
20 | with:
21 | python-version: '3.10' # Use the Python version your project needs
22 |
23 | # Install dependencies
24 | - name: Install dependencies
25 | run: |
26 | python -m pip install --upgrade pip
27 | pip install -r requirements.txt
28 | pip install lightgbm xgboost catboost # Install the libraries required for tests
29 | pip install pytest
30 |
31 | # Run tests using pytest
32 | - name: Run tests
33 | run: |
34 | pytest --maxfail=1 --disable-warnings
35 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled class file
2 | *.class
3 |
4 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
5 | hs_err_pid*
6 |
7 | #idea files
8 | *.iml
9 | *.ipr
10 | *.iws
11 | /.idea
12 |
13 | #vscode files
14 | .project
15 | .classpath
16 | /.settings
17 | /.vscode
18 |
19 | #logs
20 | /logs
21 |
22 | #build folders
23 | build/
24 | out/
25 | .gradle/
26 | bin/
27 |
28 | # Python cache files
29 | __pycache__/
30 | *.py[cod]
31 | *.pyo
32 | *.pyd
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2024 Wise PLC
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## Overview
2 | `shap-select` implements a heuristic for fast feature selection, for tabular regression and classification models.
3 |
4 | The basic idea is running a linear or logistic regression of the target on the Shapley values of
5 | the original features, on the validation set,
6 | discarding the features with negative coefficients, and ranking/filtering the rest according to their
7 | statistical significance. For motivation and details, refer to our [research paper](https://arxiv.org/abs/2410.06815) see the [example notebook](https://github.com/transferwise/shap-select/blob/main/docs/Quick%20feature%20selection%20through%20regression%20on%20Shapley%20values.ipynb)
8 |
9 | Earlier packages using Shapley values for feature selection exist, the advantages of this one are
10 | * Regression on the **validation set** to combat overfitting
11 | * Only a single fit of the original model needed
12 | * A single intuitive hyperparameter for feature selection: statistical significance
13 | * Bonferroni correction for multiclass classification
14 | * Address collinearity of (Shapley value) features by repeated (linear/logistic) regression
15 |
16 | ## Usage
17 | ```python
18 | from shap_select import shap_select
19 | # Here model is any model supported by the shap library, fitted on a different (train) dataset
20 | # Task can be regression, binary, or multiclass
21 | selected_features_df = shap_select(model, X_val, y_val, task="multiclass", threshold=0.05)
22 | ```
23 |
24 |
25 |
26 |
27 | |
28 | feature name |
29 | t-value |
30 | stat.significance |
31 | coefficient |
32 | selected |
33 |
34 |
35 |
36 |
37 | 0 |
38 | x5 |
39 | 20.211299 |
40 | 0.000000 |
41 | 1.052030 |
42 | 1 |
43 |
44 |
45 | 1 |
46 | x4 |
47 | 18.315144 |
48 | 0.000000 |
49 | 0.952416 |
50 | 1 |
51 |
52 |
53 | 2 |
54 | x3 |
55 | 6.835690 |
56 | 0.000000 |
57 | 1.098154 |
58 | 1 |
59 |
60 |
61 | 3 |
62 | x2 |
63 | 6.457140 |
64 | 0.000000 |
65 | 1.044842 |
66 | 1 |
67 |
68 |
69 | 4 |
70 | x1 |
71 | 5.530556 |
72 | 0.000000 |
73 | 0.917242 |
74 | 1 |
75 |
76 |
77 | 5 |
78 | x6 |
79 | 2.390868 |
80 | 0.016827 |
81 | 1.497983 |
82 | 1 |
83 |
84 |
85 | 6 |
86 | x7 |
87 | 0.901098 |
88 | 0.367558 |
89 | 2.865508 |
90 | 0 |
91 |
92 |
93 | 7 |
94 | x8 |
95 | 0.563214 |
96 | 0.573302 |
97 | 1.933632 |
98 | 0 |
99 |
100 |
101 | 8 |
102 | x9 |
103 | -1.607814 |
104 | 0.107908 |
105 | -4.537098 |
106 | -1 |
107 |
108 |
109 |
110 |
111 |
112 | ## Citation
113 |
114 | If you use `shap-select` in your research, please cite our paper:
115 |
116 | ```bibtex
117 | @misc{kraev2024shapselectlightweightfeatureselection,
118 | title={Shap-Select: Lightweight Feature Selection Using SHAP Values and Regression},
119 | author={Egor Kraev and Baran Koseoglu and Luca Traverso and Mohammed Topiwalla},
120 | year={2024},
121 | eprint={2410.06815},
122 | archivePrefix={arXiv},
123 | primaryClass={cs.LG},
124 | url={https://arxiv.org/abs/2410.06815},
125 | }
--------------------------------------------------------------------------------
/docs/Quick feature selection through regression on Shapley values.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "b8684862",
6 | "metadata": {},
7 | "source": [
8 | "# Quick feature selection through regression on Shapley values\n",
9 | "\n",
10 | "Feature selection for tabular models is a hard problem, and most solutions proposed for it are computationally expensive. Here we show a heuristic method that is quite computationally efficient, due to the fact that computing Shapley values on tree-based models (such as XGBoost, LightGBM, or CatBoost) is quite quick. \n",
11 | "\n",
12 | "For those who haven't come across them before, Shapley values are simply a way of decomposing a model's output into contributions from the individual feature values, with the nice property that all the features' contributions are guaranteed to add up to the model output. \n",
13 | "\n",
14 | "The process goes as follows: first, you split your dataset into a training and a validation set, and train a tree-based model on the training set, using all the available features, ideally with early stopping. If you already have a model thus fitted, you can just use that instead.\n",
15 | "\n",
16 | "In the second step, you calculate the Shapley values of all the features for that model, on the validation set. And now comes the fun part: for every data point in the validation set the Shapley values add up, by construction, to the model output for that data point. \n",
17 | "\n",
18 | "Now you are in linear country. As the next step, you run a regression of the target value on the shapley values of the features, on the validation set. If the model was perfect (model output identical to target) all the regression coefficients would be equal to 1.0. In practice, that will not be the case, and the coefficients of irrelevant features end up either being statistically insignificant (because the contributions of those features don't, on average, bring the model output closer to the target on the validation set), or negative, indicating that their presence is actually harming validation set performance.\n",
19 | "\n",
20 | "So our algorithm recommends first discarding all features with negative coefficients, then ranking the rest according to their statistical significance, and choosing some significance threshold (default 5%) getting below which will make us keep the feature. \n",
21 | "\n",
22 | "Here's an example on synthetic data:"
23 | ]
24 | },
25 | {
26 | "cell_type": "code",
27 | "execution_count": 1,
28 | "id": "51cd6a7d",
29 | "metadata": {},
30 | "outputs": [],
31 | "source": [
32 | "import os, sys\n",
33 | "from typing import List\n",
34 | "\n",
35 | "import numpy as np\n",
36 | "import pandas as pd\n",
37 | "from sklearn.model_selection import train_test_split\n",
38 | "\n",
39 | "try:\n",
40 | " from shap_select import shap_select\n",
41 | "except ModuleNotFoundError:\n",
42 | " # If you're running shap_select from source\n",
43 | " root = os.path.realpath(\"..\")\n",
44 | " sys.path.append(root)\n",
45 | " from shap_select import shap_select"
46 | ]
47 | },
48 | {
49 | "cell_type": "code",
50 | "execution_count": 2,
51 | "id": "348c2468",
52 | "metadata": {},
53 | "outputs": [],
54 | "source": [
55 | "np.random.seed(42)\n",
56 | "n_samples = 100000\n",
57 | "\n",
58 | "# Create 9 normally distributed features\n",
59 | "X = pd.DataFrame(\n",
60 | " {\n",
61 | " \"x1\": np.random.normal(size=n_samples),\n",
62 | " \"x2\": np.random.normal(size=n_samples),\n",
63 | " \"x3\": np.random.normal(size=n_samples),\n",
64 | " \"x4\": np.random.normal(size=n_samples),\n",
65 | " \"x5\": np.random.normal(size=n_samples),\n",
66 | " \"x6\": np.random.normal(size=n_samples),\n",
67 | " \"x7\": np.random.normal(size=n_samples),\n",
68 | " \"x8\": np.random.normal(size=n_samples),\n",
69 | " \"x9\": np.random.normal(size=n_samples),\n",
70 | " }\n",
71 | ")\n",
72 | "\n",
73 | "# Make all the features positive-ish\n",
74 | "X += 3\n",
75 | "\n",
76 | "# Define the target based on the formula y = x1 + x2*x3 + x4*x5*x6\n",
77 | "y = (\n",
78 | " 3 * X[\"x1\"]\n",
79 | " + X[\"x2\"] * X[\"x3\"]\n",
80 | " + X[\"x4\"] * X[\"x5\"] * X[\"x6\"]\n",
81 | " + 10 * np.random.normal(size=n_samples) # lots of noise\n",
82 | ")\n",
83 | "X[\"x6\"] *= 0.1\n",
84 | "X[\"x6\"] += np.random.normal(size=n_samples)\n",
85 | "\n",
86 | "# Split the dataset into training and validation sets (both with 10K rows)\n",
87 | "X_train, X_val, y_train, y_val = train_test_split(\n",
88 | " X, y, test_size=0.1, random_state=42\n",
89 | ")"
90 | ]
91 | },
92 | {
93 | "cell_type": "markdown",
94 | "id": "fb991c51",
95 | "metadata": {},
96 | "source": [
97 | "Let's train, for example, an xgboost model on the training set:"
98 | ]
99 | },
100 | {
101 | "cell_type": "code",
102 | "execution_count": 3,
103 | "id": "ec03ff2c",
104 | "metadata": {},
105 | "outputs": [
106 | {
107 | "name": "stdout",
108 | "output_type": "stream",
109 | "text": [
110 | "[0]\tvalid-rmse:17.78711\n",
111 | "[1]\tvalid-rmse:16.44843\n",
112 | "[2]\tvalid-rmse:15.64895\n",
113 | "[3]\tvalid-rmse:15.19588\n",
114 | "[4]\tvalid-rmse:14.92683\n",
115 | "[5]\tvalid-rmse:14.75290\n",
116 | "[6]\tvalid-rmse:14.65225\n",
117 | "[7]\tvalid-rmse:14.56790\n",
118 | "[8]\tvalid-rmse:14.50784\n",
119 | "[9]\tvalid-rmse:14.46584\n",
120 | "[10]\tvalid-rmse:14.43859\n",
121 | "[11]\tvalid-rmse:14.42790\n",
122 | "[12]\tvalid-rmse:14.41093\n",
123 | "[13]\tvalid-rmse:14.39674\n",
124 | "[14]\tvalid-rmse:14.38603\n",
125 | "[15]\tvalid-rmse:14.38173\n",
126 | "[16]\tvalid-rmse:14.37627\n",
127 | "[17]\tvalid-rmse:14.37386\n",
128 | "[18]\tvalid-rmse:14.36957\n",
129 | "[19]\tvalid-rmse:14.36874\n",
130 | "[20]\tvalid-rmse:14.36958\n",
131 | "[21]\tvalid-rmse:14.37481\n",
132 | "[22]\tvalid-rmse:14.37414\n",
133 | "[23]\tvalid-rmse:14.37449\n",
134 | "[24]\tvalid-rmse:14.37473\n",
135 | "[25]\tvalid-rmse:14.37843\n",
136 | "[26]\tvalid-rmse:14.38056\n",
137 | "[27]\tvalid-rmse:14.38592\n",
138 | "[28]\tvalid-rmse:14.39205\n",
139 | "[29]\tvalid-rmse:14.39171\n",
140 | "[30]\tvalid-rmse:14.38889\n",
141 | "[31]\tvalid-rmse:14.39872\n",
142 | "[32]\tvalid-rmse:14.40221\n",
143 | "[33]\tvalid-rmse:14.40517\n",
144 | "[34]\tvalid-rmse:14.41196\n",
145 | "[35]\tvalid-rmse:14.41776\n",
146 | "[36]\tvalid-rmse:14.41830\n",
147 | "[37]\tvalid-rmse:14.42190\n",
148 | "[38]\tvalid-rmse:14.42338\n",
149 | "[39]\tvalid-rmse:14.42358\n",
150 | "[40]\tvalid-rmse:14.42555\n",
151 | "[41]\tvalid-rmse:14.42859\n",
152 | "[42]\tvalid-rmse:14.43496\n",
153 | "[43]\tvalid-rmse:14.43931\n",
154 | "[44]\tvalid-rmse:14.44010\n",
155 | "[45]\tvalid-rmse:14.44360\n",
156 | "[46]\tvalid-rmse:14.44819\n",
157 | "[47]\tvalid-rmse:14.45216\n",
158 | "[48]\tvalid-rmse:14.45540\n",
159 | "[49]\tvalid-rmse:14.46038\n",
160 | "[50]\tvalid-rmse:14.46093\n",
161 | "[51]\tvalid-rmse:14.46455\n",
162 | "[52]\tvalid-rmse:14.46794\n",
163 | "[53]\tvalid-rmse:14.47515\n",
164 | "[54]\tvalid-rmse:14.48102\n",
165 | "[55]\tvalid-rmse:14.48300\n",
166 | "[56]\tvalid-rmse:14.48801\n",
167 | "[57]\tvalid-rmse:14.49156\n",
168 | "[58]\tvalid-rmse:14.48867\n",
169 | "[59]\tvalid-rmse:14.49315\n",
170 | "[60]\tvalid-rmse:14.49491\n",
171 | "[61]\tvalid-rmse:14.49620\n",
172 | "[62]\tvalid-rmse:14.50005\n",
173 | "[63]\tvalid-rmse:14.50803\n",
174 | "[64]\tvalid-rmse:14.51442\n",
175 | "[65]\tvalid-rmse:14.51705\n",
176 | "[66]\tvalid-rmse:14.52365\n",
177 | "[67]\tvalid-rmse:14.52792\n",
178 | "[68]\tvalid-rmse:14.53296\n"
179 | ]
180 | }
181 | ],
182 | "source": [
183 | "import xgboost as xgb\n",
184 | "\n",
185 | "dtrain = xgb.DMatrix(X_train, label=y_train)\n",
186 | "dval = xgb.DMatrix(X_val, label=y_val)\n",
187 | "params = {\n",
188 | " \"objective\": \"reg:squarederror\",\n",
189 | " \"eval_metric\": \"rmse\",\n",
190 | " \"verbosity\": 0,\n",
191 | " }\n",
192 | "\n",
193 | "model = xgb.train(\n",
194 | " params, dtrain, num_boost_round=1000, evals= [(dval, \"valid\")], early_stopping_rounds=50\n",
195 | ")"
196 | ]
197 | },
198 | {
199 | "cell_type": "markdown",
200 | "id": "0fbd335f",
201 | "metadata": {},
202 | "source": [
203 | "Now let's generate the feature significance scores. The final column shows whether we suggest to select the feature; -1 means feature is rejected because of a negative regression coefficient, 0 means it's rejected because of not passing the significance threshold."
204 | ]
205 | },
206 | {
207 | "cell_type": "code",
208 | "execution_count": 4,
209 | "id": "8f403fc5",
210 | "metadata": {},
211 | "outputs": [],
212 | "source": [
213 | "selected_features_df = shap_select(model, X_val, y_val, task=\"regression\", threshold=0.05)"
214 | ]
215 | },
216 | {
217 | "cell_type": "code",
218 | "execution_count": 5,
219 | "id": "9fe28e6b",
220 | "metadata": {},
221 | "outputs": [
222 | {
223 | "data": {
224 | "text/html": [
225 | "\n",
303 | "\n",
304 | " \n",
305 | " \n",
306 | " | \n",
307 | " feature name | \n",
308 | " t-value | \n",
309 | " stat.significance | \n",
310 | " coefficient | \n",
311 | " selected | \n",
312 | "
\n",
313 | " \n",
314 | " \n",
315 | " \n",
316 | " 0 | \n",
317 | " x5 | \n",
318 | " 20.211299 | \n",
319 | " 0.000000 | \n",
320 | " 1.052030 | \n",
321 | " 1 | \n",
322 | "
\n",
323 | " \n",
324 | " 1 | \n",
325 | " x4 | \n",
326 | " 18.315144 | \n",
327 | " 0.000000 | \n",
328 | " 0.952416 | \n",
329 | " 1 | \n",
330 | "
\n",
331 | " \n",
332 | " 2 | \n",
333 | " x3 | \n",
334 | " 6.835690 | \n",
335 | " 0.000000 | \n",
336 | " 1.098154 | \n",
337 | " 1 | \n",
338 | "
\n",
339 | " \n",
340 | " 3 | \n",
341 | " x2 | \n",
342 | " 6.457140 | \n",
343 | " 0.000000 | \n",
344 | " 1.044842 | \n",
345 | " 1 | \n",
346 | "
\n",
347 | " \n",
348 | " 4 | \n",
349 | " x1 | \n",
350 | " 5.530556 | \n",
351 | " 0.000000 | \n",
352 | " 0.917242 | \n",
353 | " 1 | \n",
354 | "
\n",
355 | " \n",
356 | " 5 | \n",
357 | " x6 | \n",
358 | " 2.390868 | \n",
359 | " 0.016827 | \n",
360 | " 1.497983 | \n",
361 | " 1 | \n",
362 | "
\n",
363 | " \n",
364 | " 6 | \n",
365 | " x7 | \n",
366 | " 0.901098 | \n",
367 | " 0.367558 | \n",
368 | " 2.865508 | \n",
369 | " 0 | \n",
370 | "
\n",
371 | " \n",
372 | " 7 | \n",
373 | " x8 | \n",
374 | " 0.563214 | \n",
375 | " 0.573302 | \n",
376 | " 1.933632 | \n",
377 | " 0 | \n",
378 | "
\n",
379 | " \n",
380 | " 8 | \n",
381 | " x9 | \n",
382 | " -1.607814 | \n",
383 | " 0.107908 | \n",
384 | " -4.537098 | \n",
385 | " -1 | \n",
386 | "
\n",
387 | " \n",
388 | "
\n"
389 | ],
390 | "text/plain": [
391 | ""
392 | ]
393 | },
394 | "execution_count": 5,
395 | "metadata": {},
396 | "output_type": "execute_result"
397 | }
398 | ],
399 | "source": [
400 | "# Let's color the output prettily\n",
401 | "def prettify(df: pd.DataFrame, exclude: List[str]):\n",
402 | " styled_df = df.style.background_gradient(\n",
403 | " cmap='coolwarm', subset=pd.IndexSlice[:, [c for i,c in enumerate(df.columns) if c not in exclude]]\n",
404 | " )\n",
405 | " return styled_df\n",
406 | "\n",
407 | "prettify(selected_features_df, exclude=[\"feature name\"])"
408 | ]
409 | },
410 | {
411 | "cell_type": "markdown",
412 | "id": "6e6f6f51",
413 | "metadata": {},
414 | "source": [
415 | "## What about classifier models?\n",
416 | "You'll be happy to hear that the above approach works just fine on the classifier models. There is a slight difference under the hood, described below, but both the function call, and the interpretation of the output, work exactly the same. \n",
417 | "\n",
418 | "### Technical details for classifier models\n",
419 | "The `shap` package automatically regcognizes whether it's given a classifier model, and in that case, calculates the shap values for log odds of a particular outcome.\n",
420 | "\n",
421 | "In the case of a binary classifier, this means that we now have to run a logistic, rather than a linear regression, and then proceed exactly like before with interpreting the coefficients and significances.\n",
422 | "\n",
423 | "In the case of a multiclass classifier, we get shapley values for each value of the target; we run a binary regression for each and then for each coefficient take the largest t-value across these regresssions, and calculate the statistical significance from that. Finally, to avoid the data mining effect of multiple tests, we apply the Bonferroni correction by multiplying the resulting significance by the number of classes; this way, you can compare that value to the original threshold value. \n",
424 | "\n",
425 | "Below is an example of a multiclass classifier.\n"
426 | ]
427 | },
428 | {
429 | "cell_type": "code",
430 | "execution_count": 6,
431 | "id": "1412da7f",
432 | "metadata": {},
433 | "outputs": [
434 | {
435 | "name": "stdout",
436 | "output_type": "stream",
437 | "text": [
438 | "[0]\tvalid-mlogloss:0.78966\n",
439 | "[1]\tvalid-mlogloss:0.60695\n",
440 | "[2]\tvalid-mlogloss:0.48586\n",
441 | "[3]\tvalid-mlogloss:0.40006\n",
442 | "[4]\tvalid-mlogloss:0.33654\n",
443 | "[5]\tvalid-mlogloss:0.28842\n",
444 | "[6]\tvalid-mlogloss:0.25138\n",
445 | "[7]\tvalid-mlogloss:0.22226\n",
446 | "[8]\tvalid-mlogloss:0.19882\n",
447 | "[9]\tvalid-mlogloss:0.17992\n",
448 | "[10]\tvalid-mlogloss:0.16560\n",
449 | "[11]\tvalid-mlogloss:0.15291\n",
450 | "[12]\tvalid-mlogloss:0.14259\n",
451 | "[13]\tvalid-mlogloss:0.13417\n",
452 | "[14]\tvalid-mlogloss:0.12714\n",
453 | "[15]\tvalid-mlogloss:0.12163\n",
454 | "[16]\tvalid-mlogloss:0.11609\n",
455 | "[17]\tvalid-mlogloss:0.11109\n",
456 | "[18]\tvalid-mlogloss:0.10706\n",
457 | "[19]\tvalid-mlogloss:0.10308\n",
458 | "[20]\tvalid-mlogloss:0.09909\n",
459 | "[21]\tvalid-mlogloss:0.09610\n",
460 | "[22]\tvalid-mlogloss:0.09318\n",
461 | "[23]\tvalid-mlogloss:0.09023\n",
462 | "[24]\tvalid-mlogloss:0.08807\n",
463 | "[25]\tvalid-mlogloss:0.08563\n",
464 | "[26]\tvalid-mlogloss:0.08399\n",
465 | "[27]\tvalid-mlogloss:0.08230\n",
466 | "[28]\tvalid-mlogloss:0.08096\n",
467 | "[29]\tvalid-mlogloss:0.07934\n",
468 | "[30]\tvalid-mlogloss:0.07750\n",
469 | "[31]\tvalid-mlogloss:0.07608\n",
470 | "[32]\tvalid-mlogloss:0.07493\n",
471 | "[33]\tvalid-mlogloss:0.07354\n",
472 | "[34]\tvalid-mlogloss:0.07225\n",
473 | "[35]\tvalid-mlogloss:0.07103\n",
474 | "[36]\tvalid-mlogloss:0.06991\n",
475 | "[37]\tvalid-mlogloss:0.06901\n",
476 | "[38]\tvalid-mlogloss:0.06810\n",
477 | "[39]\tvalid-mlogloss:0.06741\n",
478 | "[40]\tvalid-mlogloss:0.06636\n",
479 | "[41]\tvalid-mlogloss:0.06560\n",
480 | "[42]\tvalid-mlogloss:0.06488\n",
481 | "[43]\tvalid-mlogloss:0.06392\n",
482 | "[44]\tvalid-mlogloss:0.06308\n",
483 | "[45]\tvalid-mlogloss:0.06232\n",
484 | "[46]\tvalid-mlogloss:0.06155\n",
485 | "[47]\tvalid-mlogloss:0.06099\n",
486 | "[48]\tvalid-mlogloss:0.06039\n",
487 | "[49]\tvalid-mlogloss:0.05985\n",
488 | "[50]\tvalid-mlogloss:0.05917\n",
489 | "[51]\tvalid-mlogloss:0.05860\n",
490 | "[52]\tvalid-mlogloss:0.05800\n",
491 | "[53]\tvalid-mlogloss:0.05757\n",
492 | "[54]\tvalid-mlogloss:0.05691\n",
493 | "[55]\tvalid-mlogloss:0.05645\n",
494 | "[56]\tvalid-mlogloss:0.05576\n",
495 | "[57]\tvalid-mlogloss:0.05521\n",
496 | "[58]\tvalid-mlogloss:0.05475\n",
497 | "[59]\tvalid-mlogloss:0.05439\n",
498 | "[60]\tvalid-mlogloss:0.05391\n",
499 | "[61]\tvalid-mlogloss:0.05366\n",
500 | "[62]\tvalid-mlogloss:0.05341\n",
501 | "[63]\tvalid-mlogloss:0.05308\n",
502 | "[64]\tvalid-mlogloss:0.05264\n",
503 | "[65]\tvalid-mlogloss:0.05230\n",
504 | "[66]\tvalid-mlogloss:0.05187\n",
505 | "[67]\tvalid-mlogloss:0.05153\n",
506 | "[68]\tvalid-mlogloss:0.05135\n",
507 | "[69]\tvalid-mlogloss:0.05105\n",
508 | "[70]\tvalid-mlogloss:0.05064\n",
509 | "[71]\tvalid-mlogloss:0.05037\n",
510 | "[72]\tvalid-mlogloss:0.05008\n",
511 | "[73]\tvalid-mlogloss:0.04967\n",
512 | "[74]\tvalid-mlogloss:0.04939\n",
513 | "[75]\tvalid-mlogloss:0.04920\n",
514 | "[76]\tvalid-mlogloss:0.04898\n",
515 | "[77]\tvalid-mlogloss:0.04861\n",
516 | "[78]\tvalid-mlogloss:0.04828\n",
517 | "[79]\tvalid-mlogloss:0.04803\n",
518 | "[80]\tvalid-mlogloss:0.04779\n",
519 | "[81]\tvalid-mlogloss:0.04741\n",
520 | "[82]\tvalid-mlogloss:0.04711\n",
521 | "[83]\tvalid-mlogloss:0.04689\n",
522 | "[84]\tvalid-mlogloss:0.04659\n",
523 | "[85]\tvalid-mlogloss:0.04630\n",
524 | "[86]\tvalid-mlogloss:0.04615\n",
525 | "[87]\tvalid-mlogloss:0.04597\n",
526 | "[88]\tvalid-mlogloss:0.04580\n",
527 | "[89]\tvalid-mlogloss:0.04563\n",
528 | "[90]\tvalid-mlogloss:0.04547\n",
529 | "[91]\tvalid-mlogloss:0.04522\n",
530 | "[92]\tvalid-mlogloss:0.04514\n",
531 | "[93]\tvalid-mlogloss:0.04479\n",
532 | "[94]\tvalid-mlogloss:0.04464\n",
533 | "[95]\tvalid-mlogloss:0.04441\n",
534 | "[96]\tvalid-mlogloss:0.04428\n",
535 | "[97]\tvalid-mlogloss:0.04415\n",
536 | "[98]\tvalid-mlogloss:0.04398\n",
537 | "[99]\tvalid-mlogloss:0.04376\n",
538 | "[100]\tvalid-mlogloss:0.04360\n",
539 | "[101]\tvalid-mlogloss:0.04344\n",
540 | "[102]\tvalid-mlogloss:0.04332\n",
541 | "[103]\tvalid-mlogloss:0.04308\n",
542 | "[104]\tvalid-mlogloss:0.04300\n",
543 | "[105]\tvalid-mlogloss:0.04283\n",
544 | "[106]\tvalid-mlogloss:0.04268\n",
545 | "[107]\tvalid-mlogloss:0.04245\n",
546 | "[108]\tvalid-mlogloss:0.04237\n",
547 | "[109]\tvalid-mlogloss:0.04230\n",
548 | "[110]\tvalid-mlogloss:0.04219\n",
549 | "[111]\tvalid-mlogloss:0.04209\n",
550 | "[112]\tvalid-mlogloss:0.04200\n",
551 | "[113]\tvalid-mlogloss:0.04184\n",
552 | "[114]\tvalid-mlogloss:0.04164\n",
553 | "[115]\tvalid-mlogloss:0.04151\n",
554 | "[116]\tvalid-mlogloss:0.04123\n",
555 | "[117]\tvalid-mlogloss:0.04102\n",
556 | "[118]\tvalid-mlogloss:0.04090\n",
557 | "[119]\tvalid-mlogloss:0.04084\n",
558 | "[120]\tvalid-mlogloss:0.04073\n",
559 | "[121]\tvalid-mlogloss:0.04057\n",
560 | "[122]\tvalid-mlogloss:0.04041\n",
561 | "[123]\tvalid-mlogloss:0.04028\n",
562 | "[124]\tvalid-mlogloss:0.04016\n",
563 | "[125]\tvalid-mlogloss:0.04005\n",
564 | "[126]\tvalid-mlogloss:0.04000\n",
565 | "[127]\tvalid-mlogloss:0.04000\n",
566 | "[128]\tvalid-mlogloss:0.03991\n",
567 | "[129]\tvalid-mlogloss:0.03964\n",
568 | "[130]\tvalid-mlogloss:0.03946\n",
569 | "[131]\tvalid-mlogloss:0.03939\n",
570 | "[132]\tvalid-mlogloss:0.03937\n",
571 | "[133]\tvalid-mlogloss:0.03936\n",
572 | "[134]\tvalid-mlogloss:0.03929\n",
573 | "[135]\tvalid-mlogloss:0.03911\n",
574 | "[136]\tvalid-mlogloss:0.03905\n",
575 | "[137]\tvalid-mlogloss:0.03900\n",
576 | "[138]\tvalid-mlogloss:0.03894\n",
577 | "[139]\tvalid-mlogloss:0.03881\n",
578 | "[140]\tvalid-mlogloss:0.03878\n",
579 | "[141]\tvalid-mlogloss:0.03858\n",
580 | "[142]\tvalid-mlogloss:0.03846\n",
581 | "[143]\tvalid-mlogloss:0.03838\n",
582 | "[144]\tvalid-mlogloss:0.03825\n",
583 | "[145]\tvalid-mlogloss:0.03816\n",
584 | "[146]\tvalid-mlogloss:0.03812\n",
585 | "[147]\tvalid-mlogloss:0.03797\n",
586 | "[148]\tvalid-mlogloss:0.03789\n",
587 | "[149]\tvalid-mlogloss:0.03784\n",
588 | "[150]\tvalid-mlogloss:0.03786\n",
589 | "[151]\tvalid-mlogloss:0.03780\n",
590 | "[152]\tvalid-mlogloss:0.03765\n",
591 | "[153]\tvalid-mlogloss:0.03759\n",
592 | "[154]\tvalid-mlogloss:0.03744\n",
593 | "[155]\tvalid-mlogloss:0.03731\n",
594 | "[156]\tvalid-mlogloss:0.03719\n",
595 | "[157]\tvalid-mlogloss:0.03724\n",
596 | "[158]\tvalid-mlogloss:0.03719\n",
597 | "[159]\tvalid-mlogloss:0.03719\n",
598 | "[160]\tvalid-mlogloss:0.03705\n",
599 | "[161]\tvalid-mlogloss:0.03698\n",
600 | "[162]\tvalid-mlogloss:0.03683\n",
601 | "[163]\tvalid-mlogloss:0.03680\n",
602 | "[164]\tvalid-mlogloss:0.03668\n",
603 | "[165]\tvalid-mlogloss:0.03664\n",
604 | "[166]\tvalid-mlogloss:0.03659\n",
605 | "[167]\tvalid-mlogloss:0.03663\n",
606 | "[168]\tvalid-mlogloss:0.03649\n",
607 | "[169]\tvalid-mlogloss:0.03638\n",
608 | "[170]\tvalid-mlogloss:0.03639\n",
609 | "[171]\tvalid-mlogloss:0.03632\n",
610 | "[172]\tvalid-mlogloss:0.03626\n",
611 | "[173]\tvalid-mlogloss:0.03621\n",
612 | "[174]\tvalid-mlogloss:0.03615\n",
613 | "[175]\tvalid-mlogloss:0.03608\n",
614 | "[176]\tvalid-mlogloss:0.03604\n",
615 | "[177]\tvalid-mlogloss:0.03595\n",
616 | "[178]\tvalid-mlogloss:0.03592\n",
617 | "[179]\tvalid-mlogloss:0.03589\n",
618 | "[180]\tvalid-mlogloss:0.03588\n",
619 | "[181]\tvalid-mlogloss:0.03578\n",
620 | "[182]\tvalid-mlogloss:0.03576\n",
621 | "[183]\tvalid-mlogloss:0.03565\n",
622 | "[184]\tvalid-mlogloss:0.03568\n",
623 | "[185]\tvalid-mlogloss:0.03560\n",
624 | "[186]\tvalid-mlogloss:0.03550\n",
625 | "[187]\tvalid-mlogloss:0.03550\n",
626 | "[188]\tvalid-mlogloss:0.03537\n",
627 | "[189]\tvalid-mlogloss:0.03534\n",
628 | "[190]\tvalid-mlogloss:0.03527\n",
629 | "[191]\tvalid-mlogloss:0.03524\n",
630 | "[192]\tvalid-mlogloss:0.03523\n",
631 | "[193]\tvalid-mlogloss:0.03520\n",
632 | "[194]\tvalid-mlogloss:0.03515\n",
633 | "[195]\tvalid-mlogloss:0.03507\n",
634 | "[196]\tvalid-mlogloss:0.03508\n",
635 | "[197]\tvalid-mlogloss:0.03499\n",
636 | "[198]\tvalid-mlogloss:0.03492\n",
637 | "[199]\tvalid-mlogloss:0.03490\n",
638 | "[200]\tvalid-mlogloss:0.03494\n",
639 | "[201]\tvalid-mlogloss:0.03484\n",
640 | "[202]\tvalid-mlogloss:0.03477\n",
641 | "[203]\tvalid-mlogloss:0.03466\n",
642 | "[204]\tvalid-mlogloss:0.03457\n",
643 | "[205]\tvalid-mlogloss:0.03453\n",
644 | "[206]\tvalid-mlogloss:0.03444\n",
645 | "[207]\tvalid-mlogloss:0.03440\n",
646 | "[208]\tvalid-mlogloss:0.03437\n",
647 | "[209]\tvalid-mlogloss:0.03427\n",
648 | "[210]\tvalid-mlogloss:0.03427\n",
649 | "[211]\tvalid-mlogloss:0.03427\n",
650 | "[212]\tvalid-mlogloss:0.03420\n",
651 | "[213]\tvalid-mlogloss:0.03423\n",
652 | "[214]\tvalid-mlogloss:0.03418\n",
653 | "[215]\tvalid-mlogloss:0.03413\n",
654 | "[216]\tvalid-mlogloss:0.03412\n",
655 | "[217]\tvalid-mlogloss:0.03408\n",
656 | "[218]\tvalid-mlogloss:0.03406\n",
657 | "[219]\tvalid-mlogloss:0.03401\n",
658 | "[220]\tvalid-mlogloss:0.03406\n",
659 | "[221]\tvalid-mlogloss:0.03412\n",
660 | "[222]\tvalid-mlogloss:0.03407\n",
661 | "[223]\tvalid-mlogloss:0.03401\n",
662 | "[224]\tvalid-mlogloss:0.03399\n",
663 | "[225]\tvalid-mlogloss:0.03393\n",
664 | "[226]\tvalid-mlogloss:0.03393\n",
665 | "[227]\tvalid-mlogloss:0.03392\n",
666 | "[228]\tvalid-mlogloss:0.03386\n",
667 | "[229]\tvalid-mlogloss:0.03380\n",
668 | "[230]\tvalid-mlogloss:0.03377\n",
669 | "[231]\tvalid-mlogloss:0.03382\n",
670 | "[232]\tvalid-mlogloss:0.03369\n",
671 | "[233]\tvalid-mlogloss:0.03374\n",
672 | "[234]\tvalid-mlogloss:0.03364\n",
673 | "[235]\tvalid-mlogloss:0.03357\n",
674 | "[236]\tvalid-mlogloss:0.03355\n",
675 | "[237]\tvalid-mlogloss:0.03339\n",
676 | "[238]\tvalid-mlogloss:0.03335\n",
677 | "[239]\tvalid-mlogloss:0.03329\n",
678 | "[240]\tvalid-mlogloss:0.03321\n",
679 | "[241]\tvalid-mlogloss:0.03318\n",
680 | "[242]\tvalid-mlogloss:0.03319\n",
681 | "[243]\tvalid-mlogloss:0.03321\n",
682 | "[244]\tvalid-mlogloss:0.03318\n",
683 | "[245]\tvalid-mlogloss:0.03314\n",
684 | "[246]\tvalid-mlogloss:0.03308\n",
685 | "[247]\tvalid-mlogloss:0.03303\n",
686 | "[248]\tvalid-mlogloss:0.03297\n",
687 | "[249]\tvalid-mlogloss:0.03285\n",
688 | "[250]\tvalid-mlogloss:0.03286\n",
689 | "[251]\tvalid-mlogloss:0.03283\n",
690 | "[252]\tvalid-mlogloss:0.03284\n",
691 | "[253]\tvalid-mlogloss:0.03283\n",
692 | "[254]\tvalid-mlogloss:0.03279\n",
693 | "[255]\tvalid-mlogloss:0.03285\n",
694 | "[256]\tvalid-mlogloss:0.03279\n",
695 | "[257]\tvalid-mlogloss:0.03275\n",
696 | "[258]\tvalid-mlogloss:0.03277\n",
697 | "[259]\tvalid-mlogloss:0.03274\n",
698 | "[260]\tvalid-mlogloss:0.03267\n",
699 | "[261]\tvalid-mlogloss:0.03266\n",
700 | "[262]\tvalid-mlogloss:0.03262\n",
701 | "[263]\tvalid-mlogloss:0.03260\n",
702 | "[264]\tvalid-mlogloss:0.03256\n",
703 | "[265]\tvalid-mlogloss:0.03244\n",
704 | "[266]\tvalid-mlogloss:0.03250\n",
705 | "[267]\tvalid-mlogloss:0.03248\n",
706 | "[268]\tvalid-mlogloss:0.03247\n",
707 | "[269]\tvalid-mlogloss:0.03243\n",
708 | "[270]\tvalid-mlogloss:0.03245\n",
709 | "[271]\tvalid-mlogloss:0.03246\n",
710 | "[272]\tvalid-mlogloss:0.03246\n",
711 | "[273]\tvalid-mlogloss:0.03237\n",
712 | "[274]\tvalid-mlogloss:0.03234\n",
713 | "[275]\tvalid-mlogloss:0.03227\n",
714 | "[276]\tvalid-mlogloss:0.03232\n",
715 | "[277]\tvalid-mlogloss:0.03226\n",
716 | "[278]\tvalid-mlogloss:0.03224\n",
717 | "[279]\tvalid-mlogloss:0.03222\n",
718 | "[280]\tvalid-mlogloss:0.03218\n",
719 | "[281]\tvalid-mlogloss:0.03222\n",
720 | "[282]\tvalid-mlogloss:0.03218\n",
721 | "[283]\tvalid-mlogloss:0.03214\n",
722 | "[284]\tvalid-mlogloss:0.03208\n",
723 | "[285]\tvalid-mlogloss:0.03207\n"
724 | ]
725 | },
726 | {
727 | "name": "stdout",
728 | "output_type": "stream",
729 | "text": [
730 | "[286]\tvalid-mlogloss:0.03211\n",
731 | "[287]\tvalid-mlogloss:0.03207\n",
732 | "[288]\tvalid-mlogloss:0.03203\n",
733 | "[289]\tvalid-mlogloss:0.03205\n",
734 | "[290]\tvalid-mlogloss:0.03209\n",
735 | "[291]\tvalid-mlogloss:0.03205\n",
736 | "[292]\tvalid-mlogloss:0.03204\n",
737 | "[293]\tvalid-mlogloss:0.03205\n",
738 | "[294]\tvalid-mlogloss:0.03196\n",
739 | "[295]\tvalid-mlogloss:0.03193\n",
740 | "[296]\tvalid-mlogloss:0.03194\n",
741 | "[297]\tvalid-mlogloss:0.03189\n",
742 | "[298]\tvalid-mlogloss:0.03187\n",
743 | "[299]\tvalid-mlogloss:0.03189\n",
744 | "[300]\tvalid-mlogloss:0.03184\n",
745 | "[301]\tvalid-mlogloss:0.03186\n",
746 | "[302]\tvalid-mlogloss:0.03190\n",
747 | "[303]\tvalid-mlogloss:0.03187\n",
748 | "[304]\tvalid-mlogloss:0.03183\n",
749 | "[305]\tvalid-mlogloss:0.03182\n",
750 | "[306]\tvalid-mlogloss:0.03178\n",
751 | "[307]\tvalid-mlogloss:0.03175\n",
752 | "[308]\tvalid-mlogloss:0.03179\n",
753 | "[309]\tvalid-mlogloss:0.03178\n",
754 | "[310]\tvalid-mlogloss:0.03172\n",
755 | "[311]\tvalid-mlogloss:0.03169\n",
756 | "[312]\tvalid-mlogloss:0.03165\n",
757 | "[313]\tvalid-mlogloss:0.03163\n",
758 | "[314]\tvalid-mlogloss:0.03162\n",
759 | "[315]\tvalid-mlogloss:0.03161\n",
760 | "[316]\tvalid-mlogloss:0.03161\n",
761 | "[317]\tvalid-mlogloss:0.03163\n",
762 | "[318]\tvalid-mlogloss:0.03158\n",
763 | "[319]\tvalid-mlogloss:0.03153\n",
764 | "[320]\tvalid-mlogloss:0.03149\n",
765 | "[321]\tvalid-mlogloss:0.03148\n",
766 | "[322]\tvalid-mlogloss:0.03141\n",
767 | "[323]\tvalid-mlogloss:0.03139\n",
768 | "[324]\tvalid-mlogloss:0.03134\n",
769 | "[325]\tvalid-mlogloss:0.03131\n",
770 | "[326]\tvalid-mlogloss:0.03130\n",
771 | "[327]\tvalid-mlogloss:0.03126\n",
772 | "[328]\tvalid-mlogloss:0.03128\n",
773 | "[329]\tvalid-mlogloss:0.03127\n",
774 | "[330]\tvalid-mlogloss:0.03132\n",
775 | "[331]\tvalid-mlogloss:0.03133\n",
776 | "[332]\tvalid-mlogloss:0.03129\n",
777 | "[333]\tvalid-mlogloss:0.03126\n",
778 | "[334]\tvalid-mlogloss:0.03128\n",
779 | "[335]\tvalid-mlogloss:0.03123\n",
780 | "[336]\tvalid-mlogloss:0.03124\n",
781 | "[337]\tvalid-mlogloss:0.03119\n",
782 | "[338]\tvalid-mlogloss:0.03112\n",
783 | "[339]\tvalid-mlogloss:0.03114\n",
784 | "[340]\tvalid-mlogloss:0.03115\n",
785 | "[341]\tvalid-mlogloss:0.03113\n",
786 | "[342]\tvalid-mlogloss:0.03120\n",
787 | "[343]\tvalid-mlogloss:0.03118\n",
788 | "[344]\tvalid-mlogloss:0.03121\n",
789 | "[345]\tvalid-mlogloss:0.03120\n",
790 | "[346]\tvalid-mlogloss:0.03124\n",
791 | "[347]\tvalid-mlogloss:0.03120\n",
792 | "[348]\tvalid-mlogloss:0.03114\n",
793 | "[349]\tvalid-mlogloss:0.03111\n",
794 | "[350]\tvalid-mlogloss:0.03115\n",
795 | "[351]\tvalid-mlogloss:0.03109\n",
796 | "[352]\tvalid-mlogloss:0.03112\n",
797 | "[353]\tvalid-mlogloss:0.03105\n",
798 | "[354]\tvalid-mlogloss:0.03107\n",
799 | "[355]\tvalid-mlogloss:0.03105\n",
800 | "[356]\tvalid-mlogloss:0.03102\n",
801 | "[357]\tvalid-mlogloss:0.03105\n",
802 | "[358]\tvalid-mlogloss:0.03103\n",
803 | "[359]\tvalid-mlogloss:0.03103\n",
804 | "[360]\tvalid-mlogloss:0.03104\n",
805 | "[361]\tvalid-mlogloss:0.03105\n",
806 | "[362]\tvalid-mlogloss:0.03107\n",
807 | "[363]\tvalid-mlogloss:0.03105\n",
808 | "[364]\tvalid-mlogloss:0.03105\n",
809 | "[365]\tvalid-mlogloss:0.03110\n",
810 | "[366]\tvalid-mlogloss:0.03109\n",
811 | "[367]\tvalid-mlogloss:0.03109\n",
812 | "[368]\tvalid-mlogloss:0.03102\n",
813 | "[369]\tvalid-mlogloss:0.03104\n",
814 | "[370]\tvalid-mlogloss:0.03103\n",
815 | "[371]\tvalid-mlogloss:0.03106\n",
816 | "[372]\tvalid-mlogloss:0.03107\n",
817 | "[373]\tvalid-mlogloss:0.03105\n",
818 | "[374]\tvalid-mlogloss:0.03099\n",
819 | "[375]\tvalid-mlogloss:0.03097\n",
820 | "[376]\tvalid-mlogloss:0.03098\n",
821 | "[377]\tvalid-mlogloss:0.03095\n",
822 | "[378]\tvalid-mlogloss:0.03096\n",
823 | "[379]\tvalid-mlogloss:0.03099\n",
824 | "[380]\tvalid-mlogloss:0.03099\n",
825 | "[381]\tvalid-mlogloss:0.03098\n",
826 | "[382]\tvalid-mlogloss:0.03095\n",
827 | "[383]\tvalid-mlogloss:0.03095\n",
828 | "[384]\tvalid-mlogloss:0.03096\n",
829 | "[385]\tvalid-mlogloss:0.03100\n",
830 | "[386]\tvalid-mlogloss:0.03095\n",
831 | "[387]\tvalid-mlogloss:0.03087\n",
832 | "[388]\tvalid-mlogloss:0.03086\n",
833 | "[389]\tvalid-mlogloss:0.03090\n",
834 | "[390]\tvalid-mlogloss:0.03088\n",
835 | "[391]\tvalid-mlogloss:0.03092\n",
836 | "[392]\tvalid-mlogloss:0.03093\n",
837 | "[393]\tvalid-mlogloss:0.03096\n",
838 | "[394]\tvalid-mlogloss:0.03096\n",
839 | "[395]\tvalid-mlogloss:0.03097\n",
840 | "[396]\tvalid-mlogloss:0.03098\n",
841 | "[397]\tvalid-mlogloss:0.03098\n",
842 | "[398]\tvalid-mlogloss:0.03094\n",
843 | "[399]\tvalid-mlogloss:0.03094\n",
844 | "[400]\tvalid-mlogloss:0.03091\n",
845 | "[401]\tvalid-mlogloss:0.03089\n",
846 | "[402]\tvalid-mlogloss:0.03089\n",
847 | "[403]\tvalid-mlogloss:0.03088\n",
848 | "[404]\tvalid-mlogloss:0.03080\n",
849 | "[405]\tvalid-mlogloss:0.03078\n",
850 | "[406]\tvalid-mlogloss:0.03077\n",
851 | "[407]\tvalid-mlogloss:0.03076\n",
852 | "[408]\tvalid-mlogloss:0.03076\n",
853 | "[409]\tvalid-mlogloss:0.03074\n",
854 | "[410]\tvalid-mlogloss:0.03070\n",
855 | "[411]\tvalid-mlogloss:0.03065\n",
856 | "[412]\tvalid-mlogloss:0.03065\n",
857 | "[413]\tvalid-mlogloss:0.03066\n",
858 | "[414]\tvalid-mlogloss:0.03065\n",
859 | "[415]\tvalid-mlogloss:0.03065\n",
860 | "[416]\tvalid-mlogloss:0.03061\n",
861 | "[417]\tvalid-mlogloss:0.03062\n",
862 | "[418]\tvalid-mlogloss:0.03064\n",
863 | "[419]\tvalid-mlogloss:0.03060\n",
864 | "[420]\tvalid-mlogloss:0.03061\n",
865 | "[421]\tvalid-mlogloss:0.03060\n",
866 | "[422]\tvalid-mlogloss:0.03060\n",
867 | "[423]\tvalid-mlogloss:0.03063\n",
868 | "[424]\tvalid-mlogloss:0.03064\n",
869 | "[425]\tvalid-mlogloss:0.03063\n",
870 | "[426]\tvalid-mlogloss:0.03065\n",
871 | "[427]\tvalid-mlogloss:0.03067\n",
872 | "[428]\tvalid-mlogloss:0.03066\n",
873 | "[429]\tvalid-mlogloss:0.03064\n",
874 | "[430]\tvalid-mlogloss:0.03063\n",
875 | "[431]\tvalid-mlogloss:0.03062\n",
876 | "[432]\tvalid-mlogloss:0.03061\n",
877 | "[433]\tvalid-mlogloss:0.03054\n",
878 | "[434]\tvalid-mlogloss:0.03052\n",
879 | "[435]\tvalid-mlogloss:0.03050\n",
880 | "[436]\tvalid-mlogloss:0.03052\n",
881 | "[437]\tvalid-mlogloss:0.03056\n",
882 | "[438]\tvalid-mlogloss:0.03052\n",
883 | "[439]\tvalid-mlogloss:0.03057\n",
884 | "[440]\tvalid-mlogloss:0.03055\n",
885 | "[441]\tvalid-mlogloss:0.03047\n",
886 | "[442]\tvalid-mlogloss:0.03048\n",
887 | "[443]\tvalid-mlogloss:0.03052\n",
888 | "[444]\tvalid-mlogloss:0.03050\n",
889 | "[445]\tvalid-mlogloss:0.03052\n",
890 | "[446]\tvalid-mlogloss:0.03051\n",
891 | "[447]\tvalid-mlogloss:0.03051\n",
892 | "[448]\tvalid-mlogloss:0.03049\n",
893 | "[449]\tvalid-mlogloss:0.03048\n",
894 | "[450]\tvalid-mlogloss:0.03047\n",
895 | "[451]\tvalid-mlogloss:0.03047\n",
896 | "[452]\tvalid-mlogloss:0.03052\n",
897 | "[453]\tvalid-mlogloss:0.03053\n",
898 | "[454]\tvalid-mlogloss:0.03050\n",
899 | "[455]\tvalid-mlogloss:0.03055\n",
900 | "[456]\tvalid-mlogloss:0.03050\n",
901 | "[457]\tvalid-mlogloss:0.03048\n",
902 | "[458]\tvalid-mlogloss:0.03050\n",
903 | "[459]\tvalid-mlogloss:0.03053\n",
904 | "[460]\tvalid-mlogloss:0.03056\n",
905 | "[461]\tvalid-mlogloss:0.03056\n",
906 | "[462]\tvalid-mlogloss:0.03057\n",
907 | "[463]\tvalid-mlogloss:0.03054\n",
908 | "[464]\tvalid-mlogloss:0.03054\n",
909 | "[465]\tvalid-mlogloss:0.03052\n",
910 | "[466]\tvalid-mlogloss:0.03053\n",
911 | "[467]\tvalid-mlogloss:0.03054\n",
912 | "[468]\tvalid-mlogloss:0.03055\n",
913 | "[469]\tvalid-mlogloss:0.03054\n",
914 | "[470]\tvalid-mlogloss:0.03055\n",
915 | "[471]\tvalid-mlogloss:0.03056\n",
916 | "[472]\tvalid-mlogloss:0.03053\n",
917 | "[473]\tvalid-mlogloss:0.03050\n",
918 | "[474]\tvalid-mlogloss:0.03044\n",
919 | "[475]\tvalid-mlogloss:0.03047\n",
920 | "[476]\tvalid-mlogloss:0.03047\n",
921 | "[477]\tvalid-mlogloss:0.03044\n",
922 | "[478]\tvalid-mlogloss:0.03044\n",
923 | "[479]\tvalid-mlogloss:0.03045\n",
924 | "[480]\tvalid-mlogloss:0.03046\n",
925 | "[481]\tvalid-mlogloss:0.03045\n",
926 | "[482]\tvalid-mlogloss:0.03044\n",
927 | "[483]\tvalid-mlogloss:0.03048\n",
928 | "[484]\tvalid-mlogloss:0.03048\n",
929 | "[485]\tvalid-mlogloss:0.03045\n",
930 | "[486]\tvalid-mlogloss:0.03043\n",
931 | "[487]\tvalid-mlogloss:0.03046\n",
932 | "[488]\tvalid-mlogloss:0.03047\n",
933 | "[489]\tvalid-mlogloss:0.03050\n",
934 | "[490]\tvalid-mlogloss:0.03049\n",
935 | "[491]\tvalid-mlogloss:0.03048\n",
936 | "[492]\tvalid-mlogloss:0.03050\n",
937 | "[493]\tvalid-mlogloss:0.03048\n",
938 | "[494]\tvalid-mlogloss:0.03047\n",
939 | "[495]\tvalid-mlogloss:0.03053\n",
940 | "[496]\tvalid-mlogloss:0.03055\n",
941 | "[497]\tvalid-mlogloss:0.03055\n",
942 | "[498]\tvalid-mlogloss:0.03055\n",
943 | "[499]\tvalid-mlogloss:0.03049\n",
944 | "[500]\tvalid-mlogloss:0.03047\n",
945 | "[501]\tvalid-mlogloss:0.03049\n",
946 | "[502]\tvalid-mlogloss:0.03049\n",
947 | "[503]\tvalid-mlogloss:0.03049\n",
948 | "[504]\tvalid-mlogloss:0.03051\n",
949 | "[505]\tvalid-mlogloss:0.03050\n",
950 | "[506]\tvalid-mlogloss:0.03053\n",
951 | "[507]\tvalid-mlogloss:0.03053\n",
952 | "[508]\tvalid-mlogloss:0.03054\n",
953 | "[509]\tvalid-mlogloss:0.03050\n",
954 | "[510]\tvalid-mlogloss:0.03044\n",
955 | "[511]\tvalid-mlogloss:0.03045\n",
956 | "[512]\tvalid-mlogloss:0.03047\n",
957 | "[513]\tvalid-mlogloss:0.03045\n",
958 | "[514]\tvalid-mlogloss:0.03041\n",
959 | "[515]\tvalid-mlogloss:0.03040\n",
960 | "[516]\tvalid-mlogloss:0.03042\n",
961 | "[517]\tvalid-mlogloss:0.03043\n",
962 | "[518]\tvalid-mlogloss:0.03040\n",
963 | "[519]\tvalid-mlogloss:0.03044\n",
964 | "[520]\tvalid-mlogloss:0.03045\n",
965 | "[521]\tvalid-mlogloss:0.03045\n",
966 | "[522]\tvalid-mlogloss:0.03044\n",
967 | "[523]\tvalid-mlogloss:0.03040\n",
968 | "[524]\tvalid-mlogloss:0.03042\n",
969 | "[525]\tvalid-mlogloss:0.03036\n",
970 | "[526]\tvalid-mlogloss:0.03030\n",
971 | "[527]\tvalid-mlogloss:0.03033\n",
972 | "[528]\tvalid-mlogloss:0.03032\n",
973 | "[529]\tvalid-mlogloss:0.03037\n",
974 | "[530]\tvalid-mlogloss:0.03036\n",
975 | "[531]\tvalid-mlogloss:0.03035\n",
976 | "[532]\tvalid-mlogloss:0.03038\n",
977 | "[533]\tvalid-mlogloss:0.03039\n",
978 | "[534]\tvalid-mlogloss:0.03042\n",
979 | "[535]\tvalid-mlogloss:0.03041\n",
980 | "[536]\tvalid-mlogloss:0.03039\n",
981 | "[537]\tvalid-mlogloss:0.03041\n",
982 | "[538]\tvalid-mlogloss:0.03039\n",
983 | "[539]\tvalid-mlogloss:0.03034\n",
984 | "[540]\tvalid-mlogloss:0.03034\n",
985 | "[541]\tvalid-mlogloss:0.03033\n",
986 | "[542]\tvalid-mlogloss:0.03031\n",
987 | "[543]\tvalid-mlogloss:0.03029\n",
988 | "[544]\tvalid-mlogloss:0.03024\n",
989 | "[545]\tvalid-mlogloss:0.03027\n",
990 | "[546]\tvalid-mlogloss:0.03022\n",
991 | "[547]\tvalid-mlogloss:0.03025\n",
992 | "[548]\tvalid-mlogloss:0.03025\n",
993 | "[549]\tvalid-mlogloss:0.03024\n",
994 | "[550]\tvalid-mlogloss:0.03024\n",
995 | "[551]\tvalid-mlogloss:0.03023\n",
996 | "[552]\tvalid-mlogloss:0.03019\n",
997 | "[553]\tvalid-mlogloss:0.03021\n",
998 | "[554]\tvalid-mlogloss:0.03021\n",
999 | "[555]\tvalid-mlogloss:0.03017\n",
1000 | "[556]\tvalid-mlogloss:0.03015\n",
1001 | "[557]\tvalid-mlogloss:0.03015\n",
1002 | "[558]\tvalid-mlogloss:0.03016\n",
1003 | "[559]\tvalid-mlogloss:0.03016\n",
1004 | "[560]\tvalid-mlogloss:0.03020\n",
1005 | "[561]\tvalid-mlogloss:0.03019\n",
1006 | "[562]\tvalid-mlogloss:0.03021\n",
1007 | "[563]\tvalid-mlogloss:0.03018\n",
1008 | "[564]\tvalid-mlogloss:0.03021\n",
1009 | "[565]\tvalid-mlogloss:0.03016\n",
1010 | "[566]\tvalid-mlogloss:0.03011\n",
1011 | "[567]\tvalid-mlogloss:0.03015\n"
1012 | ]
1013 | },
1014 | {
1015 | "name": "stdout",
1016 | "output_type": "stream",
1017 | "text": [
1018 | "[568]\tvalid-mlogloss:0.03013\n",
1019 | "[569]\tvalid-mlogloss:0.03016\n",
1020 | "[570]\tvalid-mlogloss:0.03014\n",
1021 | "[571]\tvalid-mlogloss:0.03011\n",
1022 | "[572]\tvalid-mlogloss:0.03015\n",
1023 | "[573]\tvalid-mlogloss:0.03013\n",
1024 | "[574]\tvalid-mlogloss:0.03016\n",
1025 | "[575]\tvalid-mlogloss:0.03021\n",
1026 | "[576]\tvalid-mlogloss:0.03017\n",
1027 | "[577]\tvalid-mlogloss:0.03018\n",
1028 | "[578]\tvalid-mlogloss:0.03017\n",
1029 | "[579]\tvalid-mlogloss:0.03018\n",
1030 | "[580]\tvalid-mlogloss:0.03023\n",
1031 | "[581]\tvalid-mlogloss:0.03018\n",
1032 | "[582]\tvalid-mlogloss:0.03018\n",
1033 | "[583]\tvalid-mlogloss:0.03018\n",
1034 | "[584]\tvalid-mlogloss:0.03019\n",
1035 | "[585]\tvalid-mlogloss:0.03016\n",
1036 | "[586]\tvalid-mlogloss:0.03014\n",
1037 | "[587]\tvalid-mlogloss:0.03017\n",
1038 | "[588]\tvalid-mlogloss:0.03019\n",
1039 | "[589]\tvalid-mlogloss:0.03016\n",
1040 | "[590]\tvalid-mlogloss:0.03013\n",
1041 | "[591]\tvalid-mlogloss:0.03014\n",
1042 | "[592]\tvalid-mlogloss:0.03014\n",
1043 | "[593]\tvalid-mlogloss:0.03011\n",
1044 | "[594]\tvalid-mlogloss:0.03010\n",
1045 | "[595]\tvalid-mlogloss:0.03013\n",
1046 | "[596]\tvalid-mlogloss:0.03015\n",
1047 | "[597]\tvalid-mlogloss:0.03016\n",
1048 | "[598]\tvalid-mlogloss:0.03016\n",
1049 | "[599]\tvalid-mlogloss:0.03017\n",
1050 | "[600]\tvalid-mlogloss:0.03016\n",
1051 | "[601]\tvalid-mlogloss:0.03014\n",
1052 | "[602]\tvalid-mlogloss:0.03014\n",
1053 | "[603]\tvalid-mlogloss:0.03014\n",
1054 | "[604]\tvalid-mlogloss:0.03012\n",
1055 | "[605]\tvalid-mlogloss:0.03012\n",
1056 | "[606]\tvalid-mlogloss:0.03012\n",
1057 | "[607]\tvalid-mlogloss:0.03010\n",
1058 | "[608]\tvalid-mlogloss:0.03010\n",
1059 | "[609]\tvalid-mlogloss:0.03010\n",
1060 | "[610]\tvalid-mlogloss:0.03011\n",
1061 | "[611]\tvalid-mlogloss:0.03011\n",
1062 | "[612]\tvalid-mlogloss:0.03014\n",
1063 | "[613]\tvalid-mlogloss:0.03017\n",
1064 | "[614]\tvalid-mlogloss:0.03017\n",
1065 | "[615]\tvalid-mlogloss:0.03014\n",
1066 | "[616]\tvalid-mlogloss:0.03016\n",
1067 | "[617]\tvalid-mlogloss:0.03015\n",
1068 | "[618]\tvalid-mlogloss:0.03014\n",
1069 | "[619]\tvalid-mlogloss:0.03015\n",
1070 | "[620]\tvalid-mlogloss:0.03015\n",
1071 | "[621]\tvalid-mlogloss:0.03013\n",
1072 | "[622]\tvalid-mlogloss:0.03012\n",
1073 | "[623]\tvalid-mlogloss:0.03011\n",
1074 | "[624]\tvalid-mlogloss:0.03010\n",
1075 | "[625]\tvalid-mlogloss:0.03008\n",
1076 | "[626]\tvalid-mlogloss:0.03006\n",
1077 | "[627]\tvalid-mlogloss:0.03007\n",
1078 | "[628]\tvalid-mlogloss:0.03009\n",
1079 | "[629]\tvalid-mlogloss:0.03012\n",
1080 | "[630]\tvalid-mlogloss:0.03009\n",
1081 | "[631]\tvalid-mlogloss:0.03011\n",
1082 | "[632]\tvalid-mlogloss:0.03007\n",
1083 | "[633]\tvalid-mlogloss:0.03010\n",
1084 | "[634]\tvalid-mlogloss:0.03013\n",
1085 | "[635]\tvalid-mlogloss:0.03013\n",
1086 | "[636]\tvalid-mlogloss:0.03012\n",
1087 | "[637]\tvalid-mlogloss:0.03011\n",
1088 | "[638]\tvalid-mlogloss:0.03012\n",
1089 | "[639]\tvalid-mlogloss:0.03015\n",
1090 | "[640]\tvalid-mlogloss:0.03014\n",
1091 | "[641]\tvalid-mlogloss:0.03012\n",
1092 | "[642]\tvalid-mlogloss:0.03013\n",
1093 | "[643]\tvalid-mlogloss:0.03013\n",
1094 | "[644]\tvalid-mlogloss:0.03014\n",
1095 | "[645]\tvalid-mlogloss:0.03011\n",
1096 | "[646]\tvalid-mlogloss:0.03009\n",
1097 | "[647]\tvalid-mlogloss:0.03009\n",
1098 | "[648]\tvalid-mlogloss:0.03009\n",
1099 | "[649]\tvalid-mlogloss:0.03008\n",
1100 | "[650]\tvalid-mlogloss:0.03008\n",
1101 | "[651]\tvalid-mlogloss:0.03008\n",
1102 | "[652]\tvalid-mlogloss:0.03008\n",
1103 | "[653]\tvalid-mlogloss:0.03008\n",
1104 | "[654]\tvalid-mlogloss:0.03008\n",
1105 | "[655]\tvalid-mlogloss:0.03010\n",
1106 | "[656]\tvalid-mlogloss:0.03012\n",
1107 | "[657]\tvalid-mlogloss:0.03010\n",
1108 | "[658]\tvalid-mlogloss:0.03008\n",
1109 | "[659]\tvalid-mlogloss:0.03010\n",
1110 | "[660]\tvalid-mlogloss:0.03011\n",
1111 | "[661]\tvalid-mlogloss:0.03015\n",
1112 | "[662]\tvalid-mlogloss:0.03012\n",
1113 | "[663]\tvalid-mlogloss:0.03012\n",
1114 | "[664]\tvalid-mlogloss:0.03008\n",
1115 | "[665]\tvalid-mlogloss:0.03007\n",
1116 | "[666]\tvalid-mlogloss:0.03009\n",
1117 | "[667]\tvalid-mlogloss:0.03007\n",
1118 | "[668]\tvalid-mlogloss:0.03006\n",
1119 | "[669]\tvalid-mlogloss:0.03007\n",
1120 | "[670]\tvalid-mlogloss:0.03008\n",
1121 | "[671]\tvalid-mlogloss:0.03009\n",
1122 | "[672]\tvalid-mlogloss:0.03007\n",
1123 | "[673]\tvalid-mlogloss:0.03008\n",
1124 | "[674]\tvalid-mlogloss:0.03008\n",
1125 | "[675]\tvalid-mlogloss:0.03011\n",
1126 | "[676]\tvalid-mlogloss:0.03013\n",
1127 | "[677]\tvalid-mlogloss:0.03012\n",
1128 | "[678]\tvalid-mlogloss:0.03012\n",
1129 | "[679]\tvalid-mlogloss:0.03014\n",
1130 | "[680]\tvalid-mlogloss:0.03013\n",
1131 | "[681]\tvalid-mlogloss:0.03012\n",
1132 | "[682]\tvalid-mlogloss:0.03013\n",
1133 | "[683]\tvalid-mlogloss:0.03009\n",
1134 | "[684]\tvalid-mlogloss:0.03009\n",
1135 | "[685]\tvalid-mlogloss:0.03007\n",
1136 | "[686]\tvalid-mlogloss:0.03006\n",
1137 | "[687]\tvalid-mlogloss:0.03007\n",
1138 | "[688]\tvalid-mlogloss:0.03010\n",
1139 | "[689]\tvalid-mlogloss:0.03010\n",
1140 | "[690]\tvalid-mlogloss:0.03011\n",
1141 | "[691]\tvalid-mlogloss:0.03011\n",
1142 | "[692]\tvalid-mlogloss:0.03012\n",
1143 | "[693]\tvalid-mlogloss:0.03015\n",
1144 | "[694]\tvalid-mlogloss:0.03016\n",
1145 | "[695]\tvalid-mlogloss:0.03015\n",
1146 | "[696]\tvalid-mlogloss:0.03014\n",
1147 | "[697]\tvalid-mlogloss:0.03014\n",
1148 | "[698]\tvalid-mlogloss:0.03014\n",
1149 | "[699]\tvalid-mlogloss:0.03015\n",
1150 | "[700]\tvalid-mlogloss:0.03016\n",
1151 | "[701]\tvalid-mlogloss:0.03013\n",
1152 | "[702]\tvalid-mlogloss:0.03014\n",
1153 | "[703]\tvalid-mlogloss:0.03013\n",
1154 | "[704]\tvalid-mlogloss:0.03014\n",
1155 | "[705]\tvalid-mlogloss:0.03012\n",
1156 | "[706]\tvalid-mlogloss:0.03010\n",
1157 | "[707]\tvalid-mlogloss:0.03011\n",
1158 | "[708]\tvalid-mlogloss:0.03011\n",
1159 | "[709]\tvalid-mlogloss:0.03011\n",
1160 | "[710]\tvalid-mlogloss:0.03011\n",
1161 | "[711]\tvalid-mlogloss:0.03015\n",
1162 | "[712]\tvalid-mlogloss:0.03016\n",
1163 | "[713]\tvalid-mlogloss:0.03012\n",
1164 | "[714]\tvalid-mlogloss:0.03015\n",
1165 | "[715]\tvalid-mlogloss:0.03018\n",
1166 | "[716]\tvalid-mlogloss:0.03018\n",
1167 | "[717]\tvalid-mlogloss:0.03016\n",
1168 | "[718]\tvalid-mlogloss:0.03014\n"
1169 | ]
1170 | }
1171 | ],
1172 | "source": [
1173 | "np.random.seed(42)\n",
1174 | "n_samples = 100000\n",
1175 | "\n",
1176 | "# Create 9 normally distributed features\n",
1177 | "X = pd.DataFrame(\n",
1178 | " {\n",
1179 | " \"x1\": np.random.normal(size=n_samples),\n",
1180 | " \"x2\": np.random.normal(size=n_samples),\n",
1181 | " \"x3\": np.random.normal(size=n_samples),\n",
1182 | " \"x4\": np.random.normal(size=n_samples),\n",
1183 | " \"x5\": np.random.normal(size=n_samples),\n",
1184 | " \"x6\": np.random.normal(size=n_samples),\n",
1185 | " \"x7\": np.random.normal(size=n_samples),\n",
1186 | " \"x8\": np.random.normal(size=n_samples),\n",
1187 | " \"x9\": np.random.normal(size=n_samples),\n",
1188 | " }\n",
1189 | ")\n",
1190 | "\n",
1191 | "# Make all the features positive-ish\n",
1192 | "X += 3\n",
1193 | "\n",
1194 | "# Create a multiclass target with 3 classes\n",
1195 | "y = pd.cut(\n",
1196 | " X[\"x1\"] + X[\"x2\"] * X[\"x3\"] + X[\"x4\"] * X[\"x5\"] * X[\"x6\"],\n",
1197 | " bins=3,\n",
1198 | " labels=[0, 1, 2],\n",
1199 | ").astype(int)\n",
1200 | "\n",
1201 | "# Split the dataset into training and validation sets\n",
1202 | "X_train, X_val, y_train, y_val = train_test_split(\n",
1203 | " X, y, test_size=0.1, random_state=42\n",
1204 | ")\n",
1205 | "\n",
1206 | "dtrain = xgb.DMatrix(X_train, label=y_train)\n",
1207 | "dval = xgb.DMatrix(X_val, label=y_val)\n",
1208 | "\n",
1209 | "params = {\n",
1210 | " \"objective\": \"multi:softprob\",\n",
1211 | " \"num_class\": 3,\n",
1212 | " \"eval_metric\": \"mlogloss\",\n",
1213 | " \"verbosity\": 0,\n",
1214 | "}\n",
1215 | "\n",
1216 | "\n",
1217 | "evals = [(dval, \"valid\")]\n",
1218 | "model = xgb.train(\n",
1219 | " params, dtrain, num_boost_round=1000, evals=evals, early_stopping_rounds=50\n",
1220 | ")\n",
1221 | "\n"
1222 | ]
1223 | },
1224 | {
1225 | "cell_type": "code",
1226 | "execution_count": 7,
1227 | "id": "743d6988",
1228 | "metadata": {},
1229 | "outputs": [
1230 | {
1231 | "name": "stderr",
1232 | "output_type": "stream",
1233 | "text": [
1234 | "C:\\Users\\EgorKraev\\miniconda3\\envs\\llm3.11\\Lib\\site-packages\\sklearn\\svm\\_base.py:1235: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations.\n",
1235 | " warnings.warn(\n"
1236 | ]
1237 | },
1238 | {
1239 | "data": {
1240 | "text/html": [
1241 | "\n",
1311 | "\n",
1312 | " \n",
1313 | " \n",
1314 | " | \n",
1315 | " feature name | \n",
1316 | " t-value | \n",
1317 | " stat.significance | \n",
1318 | " coefficient | \n",
1319 | " selected | \n",
1320 | "
\n",
1321 | " \n",
1322 | " \n",
1323 | " \n",
1324 | " 0 | \n",
1325 | " x4 | \n",
1326 | " 25.927565 | \n",
1327 | " 0.000000 | \n",
1328 | " 1.559384 | \n",
1329 | " 1 | \n",
1330 | "
\n",
1331 | " \n",
1332 | " 1 | \n",
1333 | " x5 | \n",
1334 | " 25.874027 | \n",
1335 | " 0.000000 | \n",
1336 | " 1.571661 | \n",
1337 | " 1 | \n",
1338 | "
\n",
1339 | " \n",
1340 | " 2 | \n",
1341 | " x6 | \n",
1342 | " 25.782536 | \n",
1343 | " 0.000000 | \n",
1344 | " 1.561214 | \n",
1345 | " 1 | \n",
1346 | "
\n",
1347 | " \n",
1348 | " 3 | \n",
1349 | " x2 | \n",
1350 | " 21.367053 | \n",
1351 | " 0.000000 | \n",
1352 | " 1.753463 | \n",
1353 | " 1 | \n",
1354 | "
\n",
1355 | " \n",
1356 | " 4 | \n",
1357 | " x3 | \n",
1358 | " 21.330803 | \n",
1359 | " 0.000000 | \n",
1360 | " 1.792630 | \n",
1361 | " 1 | \n",
1362 | "
\n",
1363 | " \n",
1364 | " 5 | \n",
1365 | " x1 | \n",
1366 | " 12.835856 | \n",
1367 | " 0.000000 | \n",
1368 | " 2.197310 | \n",
1369 | " 1 | \n",
1370 | "
\n",
1371 | " \n",
1372 | " 6 | \n",
1373 | " x7 | \n",
1374 | " 0.773525 | \n",
1375 | " 0.658817 | \n",
1376 | " 1.901079 | \n",
1377 | " 0 | \n",
1378 | "
\n",
1379 | " \n",
1380 | " 7 | \n",
1381 | " x9 | \n",
1382 | " -0.206328 | \n",
1383 | " 1.745198 | \n",
1384 | " -0.317295 | \n",
1385 | " -1 | \n",
1386 | "
\n",
1387 | " \n",
1388 | " 8 | \n",
1389 | " x8 | \n",
1390 | " -0.636902 | \n",
1391 | " 2.213717 | \n",
1392 | " -1.259370 | \n",
1393 | " -1 | \n",
1394 | "
\n",
1395 | " \n",
1396 | "
\n"
1397 | ],
1398 | "text/plain": [
1399 | ""
1400 | ]
1401 | },
1402 | "execution_count": 7,
1403 | "metadata": {},
1404 | "output_type": "execute_result"
1405 | }
1406 | ],
1407 | "source": [
1408 | "selected_features_df = shap_select(model, X_val, y_val, task=\"multiclass\", threshold=0.05)\n",
1409 | "\n",
1410 | "prettify(selected_features_df, exclude=[\"feature name\"])"
1411 | ]
1412 | },
1413 | {
1414 | "cell_type": "code",
1415 | "execution_count": null,
1416 | "id": "60c4d878",
1417 | "metadata": {},
1418 | "outputs": [],
1419 | "source": []
1420 | }
1421 | ],
1422 | "metadata": {
1423 | "kernelspec": {
1424 | "display_name": "Python [conda env:llm3.11]",
1425 | "language": "python",
1426 | "name": "conda-env-llm3.11-py"
1427 | },
1428 | "language_info": {
1429 | "codemirror_mode": {
1430 | "name": "ipython",
1431 | "version": 3
1432 | },
1433 | "file_extension": ".py",
1434 | "mimetype": "text/x-python",
1435 | "name": "python",
1436 | "nbconvert_exporter": "python",
1437 | "pygments_lexer": "ipython3",
1438 | "version": "3.11.9"
1439 | }
1440 | },
1441 | "nbformat": 4,
1442 | "nbformat_minor": 5
1443 | }
1444 |
--------------------------------------------------------------------------------
/docs/example.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import pandas as pd
3 | import lightgbm as lgb
4 | import xgboost as xgb
5 | from sklearn.model_selection import train_test_split
6 |
7 | from shap_select import shap_select
8 |
9 | # Generate a dataset with 8 normally distributed features and a target based on a given formula
10 | np.random.seed(42)
11 | n_samples = 100000
12 |
13 | # Create 8 normally distributed features
14 | X = pd.DataFrame(
15 | {
16 | "x1": np.random.normal(size=n_samples),
17 | "x2": np.random.normal(size=n_samples),
18 | "x3": np.random.normal(size=n_samples),
19 | "x4": np.random.normal(size=n_samples),
20 | "x5": np.random.normal(size=n_samples),
21 | "x6": np.random.normal(size=n_samples),
22 | "x7": np.random.normal(size=n_samples),
23 | "x8": np.random.normal(size=n_samples),
24 | "x9": np.random.normal(size=n_samples),
25 | }
26 | )
27 |
28 | # make all the features positive-ish
29 | X += 3
30 |
31 | # Define the target based on the formula y = x1 + x2*x3 + x4*x5*x6
32 | y = (
33 | X["x1"]
34 | + X["x2"] * X["x3"]
35 | + X["x4"] * X["x5"] * X["x6"]
36 | + 10 * np.random.normal(size=n_samples) # lots of noise
37 | )
38 | X["x6"] *= 0.1
39 | X["x6"] += np.random.normal(size=n_samples)
40 |
41 | # Split the dataset into training and validation sets (both with 10K rows)
42 | X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.1, random_state=42)
43 |
44 | lightgbm = True
45 | stopping_rounds = 50
46 |
47 | if lightgbm:
48 |
49 | # Train a LightGBM model on the training data
50 | train_data = lgb.Dataset(X_train, label=y_train)
51 | val_data = lgb.Dataset(X_val, label=y_val, reference=train_data)
52 | params = {"objective": "regression", "metric": "rmse", "verbose": -1}
53 | model = lgb.train(
54 | params,
55 | train_data,
56 | num_boost_round=1000, # Max number of boosting rounds
57 | valid_sets=[train_data, val_data], # Validation sets
58 | valid_names=["train", "valid"], # Name the datasets
59 | callbacks=[
60 | lgb.early_stopping(stopping_rounds=stopping_rounds)
61 | ], # Stop if validation score doesn't improve for 10 rounds
62 | )
63 | else:
64 | dtrain = xgb.DMatrix(X_train, label=y_train)
65 | dval = xgb.DMatrix(X_val, label=y_val)
66 |
67 | # Set parameters for XGBoost
68 | params = {
69 | "objective": "reg:squarederror", # Regression task
70 | "eval_metric": "rmse", # Metric to evaluate
71 | "verbosity": 0, # Set to 0 to disable output
72 | }
73 |
74 | # Train the model with early stopping
75 | evals = [(dval, "valid")]
76 | model = xgb.train(
77 | params,
78 | dtrain,
79 | num_boost_round=1000, # Max number of boosting rounds
80 | evals=evals, # Evaluation set
81 | early_stopping_rounds=stopping_rounds, # Stop if validation RMSE doesn't improve for 10 rounds
82 | )
83 |
84 |
85 | # Call the select_features function
86 | selected_features_df, shap_features = shap_select(
87 | model, X_val, X.columns.tolist(), y_val
88 | )
89 |
90 | # Output the resulting DataFrame
91 | print(selected_features_df.head())
92 |
--------------------------------------------------------------------------------
/docs/index.md:
--------------------------------------------------------------------------------
1 | ## Repo created from the dev portal
2 |
3 | A library for feature selection for gradient boosting models using regression on feature Shapley values
4 |
5 | ## Getting started
6 |
7 | Start writing your documentation by adding more markdown (.md) files to this folder (/docs) or replace the content in this file.
8 |
9 | ## Table of Contents
10 |
11 | The Table of Contents on the right is generated automatically based on the hierarchy
12 | of headings. Only use one H1 (`#` in Markdown) per file.
13 |
14 | ## Site navigation
15 |
16 | For new pages to appear in the left hand navigation you need edit the `mkdocs.yml`
17 | file in root of your repo. The navigation can also link out to other sites.
18 |
19 | Alternatively, if there is no `nav` section in `mkdocs.yml`, a navigation section
20 | will be created for you. However, you will not be able to use alternate titles for
21 | pages, or include links to other sites.
22 |
23 | Note that MkDocs uses `mkdocs.yml`, not `mkdocs.yaml`, although both appear to work.
24 | See also .
25 |
--------------------------------------------------------------------------------
/docs/paper/benchmark.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 | import pandas as pd
3 | import numpy as np
4 | import matplotlib.pyplot as plt
5 | from boruta import BorutaPy
6 | from sklearn.feature_selection import RFE
7 | from sklearn.metrics import accuracy_score, f1_score
8 | from sklearn.model_selection import train_test_split
9 | import xgboost as xgb
10 | import time
11 | from shap_select import shap_select
12 | import hisel
13 | from shap_selection import feature_selection
14 | from skfeature.function.information_theoretical_based import MRMR
15 |
16 | RANDOM_SEED = 42
17 | np.random.seed(RANDOM_SEED)
18 |
19 | # Global XGBoost parameters for consistency
20 | XGB_PARAMS = {
21 | "objective": "binary:logistic",
22 | "eval_metric": "logloss",
23 | "verbosity": 0,
24 | "seed": RANDOM_SEED,
25 | "nthread": 1,
26 | }
27 |
28 |
29 | # Define common XGBoost model
30 | def train_xgboost(X_train, y_train):
31 | dtrain = xgb.DMatrix(X_train, label=y_train)
32 | xgb_model = xgb.train(XGB_PARAMS, dtrain, num_boost_round=100)
33 | return xgb_model
34 |
35 |
36 | def predict_xgboost(xgb_model, X_val):
37 | dval = xgb.DMatrix(X_val)
38 | y_pred = (xgb_model.predict(dval) > 0.5).astype(int)
39 | return y_pred
40 |
41 |
42 | # HISEL feature selection using MRMR
43 | def hisel_feature_selection(xgb_model, X_train, X_val, y_train, y_val, n_features):
44 | return hisel.feature_selection.select_features(X_train, y_train)
45 |
46 |
47 | def shap_selection(xgb_model, X_train, X_val, y_train, y_val, n_features) -> List[str]:
48 | selected_shap_selection, _ = feature_selection.shap_select(
49 | xgb_model, X_train, X_val, X_train.columns, agnostic=False
50 | )
51 | selected_shap_selection = selected_shap_selection[:n_features] # Why 15?
52 | return selected_shap_selection
53 |
54 |
55 | def shap_select_selection(
56 | xgb_model, X_train, X_val, y_train, y_val, n_features
57 | ) -> List[str]:
58 | shap_features, _ = shap_select(
59 | xgb_model,
60 | X_val,
61 | y_val,
62 | task="binary",
63 | alpha=1e-6,
64 | threshold=0.05,
65 | return_extended_data=True,
66 | )
67 | selected_features = shap_features[shap_features["selected"] == 1][
68 | "feature name"
69 | ].tolist()
70 | return selected_features
71 |
72 |
73 | def no_selection(xgb_model, X_train, X_val, y_train, y_val, n_features) -> List[str]:
74 | return list(X_train.columns)
75 |
76 |
77 | def rfe_selection(xgb_model, X_train, X_val, y_train, y_val, n_features) -> List[str]:
78 | rfe = RFE(
79 | xgb.XGBClassifier(**XGB_PARAMS, use_label_encoder=False),
80 | n_features_to_select=n_features,
81 | )
82 | rfe.fit(X_train, y_train)
83 | selected_rfe = X_train.columns[rfe.support_]
84 | return selected_rfe
85 |
86 |
87 | def boruta_selection(
88 | xgb_model, X_train, X_val, y_train, y_val, n_features
89 | ) -> List[str]:
90 | rf_model = xgb.XGBClassifier(**XGB_PARAMS, use_label_encoder=False)
91 | boruta_selector = BorutaPy(rf_model, n_estimators=100, random_state=RANDOM_SEED)
92 | boruta_selector.fit(X_train.values, y_train.values)
93 | selected_boruta = X_train.columns[boruta_selector.support_].tolist()
94 | return selected_boruta
95 |
96 |
97 | method_dict = {
98 | "No selection": no_selection,
99 | "shap-select": shap_select_selection,
100 | "shap-selection": shap_selection,
101 | "HISEL": hisel_feature_selection,
102 | "Boruta": boruta_selection,
103 | "RFE": rfe_selection,
104 | }
105 |
106 |
107 | # Run experiments with different feature selection methods and shap-select p-values
108 | def run_experiments(X_train, X_val, X_test, y_train, y_val, y_test):
109 | results = []
110 | pretrained_model = None
111 |
112 | for name, fun in method_dict.items():
113 | print(f"\n--- {name} ---")
114 | start_time = time.time()
115 | selected = fun(pretrained_model, X_train, X_val, y_train, y_val, n_features=15)
116 |
117 | runtime = time.time() - start_time
118 | print(
119 | f"{name} completed in {runtime:.2f} seconds with {len(selected)} features."
120 | )
121 |
122 | this_model = train_xgboost(X_train[selected], y_train)
123 |
124 | if name == "No selection":
125 | pretrained_model = this_model
126 |
127 | y_pred = predict_xgboost(this_model, X_test[selected])
128 | results.append(
129 | {
130 | "Method": name,
131 | "Selected Features": selected,
132 | "Accuracy": accuracy_score(y_test, y_pred),
133 | "F1 Score": f1_score(y_test, y_pred),
134 | "Runtime (s)": runtime,
135 | }
136 | )
137 |
138 | # assert set(X_train.columns) == set(selected_hisel), "Feature sets differ!"
139 |
140 | results_df = pd.DataFrame(results)
141 | print("\n--- Experiment Results ---")
142 | print(results_df)
143 | return results_df, pretrained_model
144 |
145 |
146 | if __name__ == "__main__":
147 | print("Loading dataset...")
148 | df = pd.read_csv("creditcard.csv")
149 | X = df.drop(columns=["Class"])
150 | y = df["Class"]
151 | # Perform a 60-20-20 split for train, validation, and test sets
152 | X_train_full, X_test, y_train_full, y_test = train_test_split(
153 | X, y, test_size=0.2, random_state=RANDOM_SEED
154 | )
155 | X_train, X_val, y_train, y_val = train_test_split(
156 | X_train_full, y_train_full, test_size=0.25, random_state=RANDOM_SEED
157 | )
158 |
159 | results_df, trained_model = run_experiments(
160 | X_train, X_val, X_test, y_train, y_val, y_test
161 | )
162 | print(results_df)
163 | print("yay!")
164 |
--------------------------------------------------------------------------------
/mkdocs.yml:
--------------------------------------------------------------------------------
1 | site_name: Repository docs
2 |
3 | nav:
4 | - Introduction: index.md
5 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | pandas
2 | scipy
3 | shap
4 | statsmodels
5 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import find_packages, setup
2 |
3 | with open("README.md") as f:
4 | long_description = f.read()
5 |
6 | setup(
7 | name="shap-select",
8 | version="0.1.0",
9 | description="Heuristic for quick feature selection for tabular regression/classification using shapley values",
10 | long_description=long_description,
11 | long_description_content_type="text/markdown",
12 | author="Wise Plc",
13 | url="https://github.com/transferwise/shap-select",
14 | classifiers=[
15 | "Programming Language :: Python :: 3 :: Only",
16 | "Programming Language :: Python :: 3.7",
17 | "Programming Language :: Python :: 3.8",
18 | "Programming Language :: Python :: 3.9",
19 | "Programming Language :: Python :: 3.10",
20 | "Programming Language :: Python :: 3.11",
21 | "Programming Language :: Python :: 3.12",
22 | ],
23 | install_requires=[
24 | "pandas",
25 | "scipy>=1.8.0",
26 | "shap",
27 | "statsmodels",
28 | ],
29 | extras_require={
30 | "test": ["flake8", "pytest", "pytest-cov"],
31 | },
32 | packages=find_packages(
33 | include=["shap_select", "shap_select.*"],
34 | exclude=["tests*"],
35 | ),
36 | include_package_data=True,
37 | keywords="shap-select",
38 | )
39 |
--------------------------------------------------------------------------------
/shap_select/__init__.py:
--------------------------------------------------------------------------------
1 | from .select import shap_select
2 |
--------------------------------------------------------------------------------
/shap_select/select.py:
--------------------------------------------------------------------------------
1 | from typing import Any, Tuple, List, Dict
2 |
3 | import pandas as pd
4 | import statsmodels.api as sm
5 | import scipy.stats as stats
6 | import shap
7 |
8 |
9 | def create_shap_features(
10 | tree_model: Any, validation_df: pd.DataFrame, classes: List | None = None
11 | ) -> pd.DataFrame | Dict[Any, pd.DataFrame]:
12 | """
13 | Generates SHAP (SHapley Additive exPlanations) values for a given tree-based model on a validation dataset.
14 |
15 | Parameters:
16 | - tree_model (Any): A trained tree-based model (e.g., XGBoost, LightGBM, or any model compatible with SHAP).
17 | - validation_df (pd.DataFrame): A DataFrame containing the validation data on which SHAP values will be computed.
18 | The DataFrame should contain the same feature columns used to train the `tree_model`.
19 |
20 | Returns:
21 | - pd.DataFrame: A DataFrame containing the SHAP values for each feature in the `validation_df`, where each column
22 | corresponds to the SHAP values of a feature, and the rows match the index of the `validation_df`.
23 | """
24 | explainer = shap.Explainer(tree_model, model_output="raw")(validation_df)
25 | shap_values = explainer.values
26 |
27 | if len(shap_values.shape) == 2:
28 | assert (
29 | classes is None
30 | ), "Don't specify classes for binary classification or regression"
31 | # Create a DataFrame with the SHAP values, with one column per feature
32 | return pd.DataFrame(
33 | shap_values, columns=validation_df.columns, index=validation_df.index
34 | )
35 | elif len(shap_values.shape) == 3: # multiclass classification
36 | out = {}
37 | for i, c in enumerate(classes):
38 | out[i] = pd.DataFrame(
39 | shap_values[:, :, i],
40 | columns=validation_df.columns,
41 | index=validation_df.index,
42 | )
43 | return out
44 |
45 |
46 | def binary_classifier_significance(
47 | shap_features: pd.DataFrame, target: pd.Series, alpha: float
48 | ) -> pd.DataFrame:
49 | """
50 | Fits a logistic regression model using the features from `shap_features` to predict the binary `target`.
51 | Returns a DataFrame containing feature names, coefficients, standard errors, and the significance (p-values).
52 |
53 | Parameters:
54 | shap_features (pd.DataFrame): A DataFrame containing the SHAP values or features used for prediction.
55 | target (pd.Series): A binary target series (0 or 1) to classify.
56 |
57 | Returns:
58 | pd.DataFrame: A DataFrame containing:
59 | - feature name: The names of the features.
60 | - coefficient: The logistic regression coefficients for each feature.
61 | - stderr: The standard error for each coefficient.
62 | - stat.significance: The p-value (statistical significance) for each feature.
63 | """
64 |
65 | # Add a constant to the features for the intercept in logistic regression
66 | shap_features_with_constant = sm.add_constant(shap_features)
67 |
68 | # Fit the logistic regression model that will generate confidence intervals
69 | logit_model = sm.Logit(target, shap_features_with_constant)
70 | result = logit_model.fit_regularized(disp=False, alpha=alpha)
71 |
72 | # Extract the results
73 | summary_frame = result.summary2().tables[1]
74 |
75 | # Create the DataFrame with the required columns
76 | result_df = pd.DataFrame(
77 | {
78 | "feature name": summary_frame.index,
79 | "coefficient": summary_frame["Coef."],
80 | "stderr": summary_frame["Std.Err."],
81 | "stat.significance": summary_frame["P>|z|"],
82 | "t-value": summary_frame["Coef."] / summary_frame["Std.Err."],
83 | }
84 | ).reset_index(drop=True)
85 | result_df["closeness to 1.0"] = (result_df["coefficient"] - 1.0).abs()
86 | return result_df.loc[~(result_df["feature name"] == "const"), :]
87 |
88 |
89 | def multi_classifier_significance(
90 | shap_features: Dict[Any, pd.DataFrame],
91 | target: pd.Series,
92 | alpha: float,
93 | return_individual_significances: bool = False,
94 | ) -> (pd.DataFrame, list):
95 | """
96 | Fits a binary logistic regression model for each unique class in the target, comparing each class against all others (one-vs-all).
97 | Calls binary_classifier_significance for each binary classification.
98 |
99 | Parameters:
100 | shap_features (pd.DataFrame): A DataFrame containing the features used for classification.
101 | target (pd.Series): A target series containing more than two classes.
102 |
103 | Returns:
104 | - A DataFrame with feature names and their maximum significance values across all binary classifications.
105 | - A list of DataFrames, one for each binary classification, containing feature names, coefficients, standard errors, and statistical significance.
106 | """
107 | significance_dfs = []
108 |
109 | # Iterate through each class and perform binary classification (one-vs-all)
110 | for cls, feature_df in shap_features.items():
111 | binary_target = (target == cls).astype(int)
112 | significance_df = binary_classifier_significance(
113 | feature_df, binary_target, alpha
114 | )
115 | significance_dfs.append(significance_df)
116 |
117 | # Combine results into a single DataFrame with the max significance value for each feature
118 | combined_df = pd.concat(significance_dfs)
119 | max_significance_df = (
120 | combined_df.groupby("feature name", as_index=False)
121 | .agg(
122 | {
123 | "t-value": "max",
124 | "closeness to 1.0": "min",
125 | "coefficient": "max",
126 | }
127 | )
128 | .reset_index(drop=True)
129 | )
130 |
131 | # Len(shap_features) multiplier is the Bonferroni correction
132 | max_significance_df["stat.significance"] = max_significance_df["t-value"].apply(
133 | lambda x: len(shap_features) * (1 - stats.norm.cdf(x))
134 | )
135 | if return_individual_significances:
136 | return max_significance_df, significance_dfs
137 | else:
138 | return max_significance_df
139 |
140 |
141 | def regression_significance(
142 | shap_features: pd.DataFrame, target: pd.Series, alpha: float
143 | ) -> pd.DataFrame:
144 | """
145 | Fits a linear regression model using the features from `shap_features` to predict the continuous `target`.
146 | Returns a DataFrame containing feature names, coefficients, standard errors, and the significance (p-values).
147 |
148 | Parameters:
149 | shap_features (pd.DataFrame): A DataFrame containing the features used for prediction.
150 | target (pd.Series): A continuous target series to predict.
151 |
152 | Returns:
153 | pd.DataFrame: A DataFrame containing:
154 | - feature name: The names of the features.
155 | - coefficient: The linear regression coefficients for each feature.
156 | - stderr: The standard error for each coefficient.
157 | - stat.significance: The p-value (statistical significance) for each feature.
158 | """
159 | # Fit the linear regression model that will generate confidence intervals
160 | ols_model = sm.OLS(target, shap_features)
161 | result = ols_model.fit_regularized(alpha=alpha, refit=True)
162 |
163 | # Extract the results
164 | summary_frame = result.summary2().tables[1]
165 |
166 | # Create the DataFrame with the required columns
167 | result_df = pd.DataFrame(
168 | {
169 | "feature name": summary_frame.index,
170 | "coefficient": summary_frame["Coef."],
171 | "stderr": summary_frame["Std.Err."],
172 | "stat.significance": summary_frame["P>|t|"],
173 | "t-value": summary_frame["Coef."] / summary_frame["Std.Err."],
174 | }
175 | ).reset_index(drop=True)
176 | result_df["closeness to 1.0"] = (result_df["coefficient"] - 1.0).abs()
177 |
178 | return result_df
179 |
180 |
181 | def closeness_to_one(df: pd.DataFrame) -> pd.Series:
182 | return (df["coefficient"] - 1.0) / df["stderr"]
183 |
184 |
185 | def shap_features_to_significance(
186 | shap_features: pd.DataFrame | List[pd.DataFrame],
187 | target: pd.Series,
188 | task: str,
189 | alpha: float,
190 | ) -> pd.DataFrame:
191 | """
192 | Determines the task (regression, binary, or multi-class classification) based on the target and calls the appropriate
193 | significance function. Returns a DataFrame with feature names and their significance values.
194 |
195 | Parameters:
196 | shap_features (pd.DataFrame): A DataFrame containing the features used for prediction.
197 | target (pd.Series): The target series for prediction (either continuous or categorical).
198 | task (str): The type of task to perform: "regression", "binary", or "multiclass".
199 |
200 | Returns:
201 | pd.DataFrame: A DataFrame containing:
202 | - feature name: The names of the features.
203 | - stat.significance: The p-value (statistical significance) for each feature.
204 | Sorted in descending order of significance (ascending p-value).
205 | """
206 |
207 | # Call the appropriate function based on the task
208 | if task == "regression":
209 | result_df = regression_significance(shap_features, target, alpha)
210 | elif task == "binary":
211 | result_df = binary_classifier_significance(shap_features, target, alpha)
212 | elif task == "multiclass":
213 | result_df = multi_classifier_significance(shap_features, target, alpha)
214 | else:
215 | raise ValueError("`task` must be 'regression', 'binary', 'multiclass' or None.")
216 |
217 | # Sort the result by statistical significance in ascending order (more significant features first)
218 | result_df_sorted = result_df.sort_values(by="t-value", ascending=False).reset_index(
219 | drop=True
220 | )
221 |
222 | return result_df_sorted
223 |
224 |
225 | def iterative_shap_feature_reduction(
226 | shap_features: pd.DataFrame | List[pd.DataFrame],
227 | target: pd.Series,
228 | task: str,
229 | alpha: float = 1e-6,
230 | ) -> pd.DataFrame:
231 | collected_rows = [] # List to store the rows we collect during each iteration
232 |
233 | features_left = True
234 | while features_left:
235 | # Call the original shap_features_to_significance function
236 | significance_df = shap_features_to_significance(
237 | shap_features, target, task, alpha
238 | )
239 |
240 | # Find the feature with the lowest t-value
241 | min_t_value_row = significance_df.loc[significance_df["t-value"].idxmin()]
242 |
243 | # Remember this row (collect it in our list)
244 | collected_rows.append(min_t_value_row)
245 |
246 | # Drop the feature corresponding to the lowest t-value from shap_features
247 | feature_to_remove = min_t_value_row["feature name"]
248 | if isinstance(shap_features, pd.DataFrame):
249 | shap_features = shap_features.drop(columns=[feature_to_remove])
250 | features_left = len(shap_features.columns)
251 | else:
252 | shap_features = {
253 | k: v.drop(columns=[feature_to_remove]) for k, v in shap_features.items()
254 | }
255 | features_left = len(list(shap_features.values())[0].columns)
256 |
257 | # Convert collected rows back to a dataframe
258 | result_df = (
259 | pd.DataFrame(collected_rows)
260 | .sort_values(by="t-value", ascending=False)
261 | .reset_index()
262 | )
263 |
264 | return result_df
265 |
266 |
267 | def shap_select(
268 | tree_model: Any,
269 | validation_df: pd.DataFrame,
270 | target: pd.Series | str, # str is column name in validation_df
271 | feature_names: List[str] | None = None,
272 | task: str | None = None,
273 | threshold: float = 0.05,
274 | return_extended_data: bool = False,
275 | alpha: float = 1e-6,
276 | ) -> pd.DataFrame | Tuple[pd.DataFrame, pd.DataFrame]:
277 | """
278 | Select features based on their SHAP values and statistical significance.
279 |
280 | Parameters:
281 | - tree_model (Any): A trained tree-based model.
282 | - validation_df (pd.DataFrame): Validation dataset containing the features.
283 | - feature_names (List[str]): A list of feature names used by the model.
284 | - target (pd.Series | str): The target values, or the name of the target column in `validation_df`.
285 | - task (str | None): The task type ('regression', 'binary', or 'multiclass'). If None, it is inferred automatically.
286 | - threshold (float): Significance threshold to select features. Default is 0.05.
287 | - return_extended_data (bool): Whether to also return the shapley values dataframe(s) and some extra columns
288 | - alpha (float): Controls the regularization strength for the regression
289 |
290 | Returns:
291 | - pd.DataFrame: A DataFrame containing the feature names, statistical significance, and a 'Selected' column
292 | indicating whether the feature was selected based on the threshold.
293 | """
294 | # If target is a string (column name), extract the target series from validation_df
295 | if isinstance(target, str):
296 | target = validation_df[target]
297 |
298 | if feature_names is None:
299 | feature_names = validation_df.columns.tolist()
300 |
301 | # Infer the task if not provided
302 | if task is None:
303 | if pd.api.types.is_numeric_dtype(target) and target.nunique() > 10:
304 | task = "regression"
305 | elif target.nunique() == 2:
306 | task = "binary"
307 | else:
308 | task = "multiclass"
309 |
310 | if task == "multiclass":
311 | unique_classes = sorted(list(target.unique()))
312 | shap_features = create_shap_features(
313 | tree_model, validation_df[feature_names], unique_classes
314 | )
315 | else:
316 | shap_features = create_shap_features(tree_model, validation_df[feature_names])
317 |
318 | # Compute statistical significance of each feature, recursively ablating
319 | significance_df = iterative_shap_feature_reduction(
320 | shap_features, target, task, alpha
321 | )
322 |
323 | # Add 'Selected' column based on the threshold
324 | significance_df["selected"] = (
325 | significance_df["stat.significance"] < threshold
326 | ).astype(int)
327 | significance_df.loc[significance_df["t-value"] < 0, "selected"] = -1
328 |
329 | if return_extended_data:
330 | return significance_df, shap_features
331 | else:
332 | return significance_df[
333 | ["feature name", "t-value", "stat.significance", "coefficient", "selected"]
334 | ]
335 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/transferwise/shap-select/5ed7030e0ff6fbc55e6bc21e9cc67d8780c93b60/tests/__init__.py
--------------------------------------------------------------------------------
/tests/test_regression.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | import numpy as np
3 | import pandas as pd
4 | import lightgbm as lgb
5 | import xgboost as xgb
6 | import catboost as cb
7 | from sklearn.model_selection import train_test_split
8 | from shap_select import shap_select
9 |
10 |
11 | @pytest.fixture
12 | def generate_data_regression():
13 | np.random.seed(42)
14 | n_samples = 100000
15 |
16 | # Create 9 normally distributed features
17 | X = pd.DataFrame(
18 | {
19 | "x1": np.random.normal(size=n_samples),
20 | "x2": np.random.normal(size=n_samples),
21 | "x3": np.random.normal(size=n_samples),
22 | "x4": np.random.normal(size=n_samples),
23 | "x5": np.random.normal(size=n_samples),
24 | "x6": np.random.normal(size=n_samples),
25 | "x7": np.random.normal(size=n_samples),
26 | "x8": np.random.normal(size=n_samples),
27 | "x9": np.random.normal(size=n_samples),
28 | }
29 | )
30 |
31 | # Make all the features positive-ish
32 | X += 3
33 |
34 | # Define the target based on the formula y = x1 + x2*x3 + x4*x5*x6
35 | y = (
36 | 3 * X["x1"]
37 | + X["x2"] * X["x3"]
38 | + X["x4"] * X["x5"] * X["x6"]
39 | + 10 * np.random.normal(size=n_samples) # lots of noise
40 | )
41 | X["x6"] *= 0.1
42 | X["x6"] += np.random.normal(size=n_samples)
43 |
44 | # Split the dataset into training and validation sets (both with 10K rows)
45 | X_train, X_val, y_train, y_val = train_test_split(
46 | X, y, test_size=0.1, random_state=42
47 | )
48 |
49 | return X_train, X_val, y_train, y_val
50 |
51 |
52 | @pytest.fixture
53 | def generate_data_binary():
54 | np.random.seed(42)
55 | n_samples = 100000
56 |
57 | # Create 9 normally distributed features
58 | X = pd.DataFrame(
59 | {
60 | "x1": np.random.normal(size=n_samples),
61 | "x2": np.random.normal(size=n_samples),
62 | "x3": np.random.normal(size=n_samples),
63 | # "x4": np.random.normal(size=n_samples),
64 | # "x5": np.random.normal(size=n_samples),
65 | # "x6": np.random.normal(size=n_samples),
66 | "x7": np.random.normal(size=n_samples),
67 | "x8": np.random.normal(size=n_samples),
68 | "x9": np.random.normal(size=n_samples),
69 | }
70 | )
71 |
72 | # Make all the features positive-ish
73 | X += 3
74 |
75 | # Create a binary target based on a threshold
76 | y = (X["x1"] + X["x2"] * X["x3"] > 12).astype(int)
77 |
78 | # Split the dataset into training and validation sets
79 | X_train, X_val, y_train, y_val = train_test_split(
80 | X, y, test_size=0.1, random_state=42
81 | )
82 |
83 | return X_train, X_val, y_train, y_val
84 |
85 |
86 | @pytest.fixture
87 | def generate_data_multiclass():
88 | np.random.seed(42)
89 | n_samples = 100000
90 |
91 | # Create 9 normally distributed features
92 | X = pd.DataFrame(
93 | {
94 | "x1": np.random.normal(size=n_samples),
95 | "x2": np.random.normal(size=n_samples),
96 | "x3": np.random.normal(size=n_samples),
97 | # "x4": np.random.normal(size=n_samples),
98 | # "x5": np.random.normal(size=n_samples),
99 | # "x6": np.random.normal(size=n_samples),
100 | "x7": np.random.normal(size=n_samples),
101 | "x8": np.random.normal(size=n_samples),
102 | "x9": np.random.normal(size=n_samples),
103 | }
104 | )
105 |
106 | # Make all the features positive-ish
107 | X += 3
108 |
109 | # Create a multiclass target with 3 classes
110 | y = pd.cut(
111 | X["x1"] + X["x2"] * X["x3"], # + X["x4"] * X["x5"] * X["x6"],
112 | bins=3,
113 | labels=[0, 1, 2],
114 | ).astype(int)
115 |
116 | # Split the dataset into training and validation sets
117 | X_train, X_val, y_train, y_val = train_test_split(
118 | X, y, test_size=0.1, random_state=42
119 | )
120 |
121 | return X_train, X_val, y_train, y_val
122 |
123 |
124 | def train_lightgbm(X_train, X_val, y_train, y_val, task_type):
125 | """Train a LightGBM model based on the task type"""
126 | train_data = lgb.Dataset(X_train, label=y_train)
127 | val_data = lgb.Dataset(X_val, label=y_val, reference=train_data)
128 |
129 | if task_type == "binary":
130 | params = {"objective": "binary", "metric": "binary_logloss", "verbose": -1}
131 | elif task_type == "regression":
132 | params = {"objective": "regression", "metric": "rmse", "verbose": -1}
133 | elif task_type == "multiclass":
134 | params = {
135 | "objective": "multiclass",
136 | "num_class": 3,
137 | "metric": "multi_logloss",
138 | "verbose": -1,
139 | }
140 | else:
141 | raise ValueError(f"Unsupported task type: {task_type}")
142 |
143 | model = lgb.train(
144 | params,
145 | train_data,
146 | num_boost_round=1000,
147 | valid_sets=[train_data, val_data],
148 | valid_names=["train", "valid"],
149 | callbacks=[lgb.early_stopping(stopping_rounds=50)],
150 | )
151 | return model
152 |
153 |
154 | def train_xgboost(X_train, X_val, y_train, y_val, task_type):
155 | """Train an XGBoost model based on the task type"""
156 | dtrain = xgb.DMatrix(X_train, label=y_train)
157 | dval = xgb.DMatrix(X_val, label=y_val)
158 |
159 | if task_type == "binary":
160 | params = {
161 | "objective": "binary:logistic",
162 | "eval_metric": "logloss",
163 | "verbosity": 0,
164 | }
165 | elif task_type == "regression":
166 | params = {
167 | "objective": "reg:squarederror",
168 | "eval_metric": "rmse",
169 | "verbosity": 0,
170 | }
171 | elif task_type == "multiclass":
172 | params = {
173 | "objective": "multi:softprob",
174 | "num_class": 3,
175 | "eval_metric": "mlogloss",
176 | "verbosity": 0,
177 | }
178 | else:
179 | raise ValueError(f"Unsupported task type: {task_type}")
180 |
181 | evals = [(dval, "valid")]
182 | model = xgb.train(
183 | params, dtrain, num_boost_round=1000, evals=evals, early_stopping_rounds=50
184 | )
185 | return model
186 |
187 |
188 | def train_catboost(X_train, X_val, y_train, y_val, task_type):
189 | """Train a CatBoost model based on the task type"""
190 | if task_type == "binary":
191 | model = cb.CatBoostClassifier(
192 | iterations=1000,
193 | loss_function="Logloss",
194 | verbose=0,
195 | early_stopping_rounds=50,
196 | )
197 | elif task_type == "regression":
198 | model = cb.CatBoostRegressor(
199 | iterations=1000, loss_function="RMSE", verbose=0, early_stopping_rounds=50
200 | )
201 | elif task_type == "multiclass":
202 | model = cb.CatBoostClassifier(
203 | iterations=1000,
204 | loss_function="MultiClass",
205 | verbose=0,
206 | early_stopping_rounds=50,
207 | )
208 | else:
209 | raise ValueError(f"Unsupported task type: {task_type}")
210 |
211 | model.fit(X_train, y_train, eval_set=(X_val, y_val), use_best_model=True)
212 | return model
213 |
214 |
215 | @pytest.mark.parametrize(
216 | "model_type",
217 | ["lightgbm", "xgboost", "catboost"],
218 | )
219 | @pytest.mark.parametrize(
220 | "data_fixture, task_type",
221 | [
222 | ("generate_data_regression", "regression"),
223 | ("generate_data_binary", "binary"),
224 | ("generate_data_multiclass", "multiclass"),
225 | ],
226 | )
227 | def test_selected_column_values(model_type, data_fixture, task_type, request):
228 | """Parameterized test for regression, binary classification, and multiclass classification."""
229 | X_train, X_val, y_train, y_val = request.getfixturevalue(data_fixture)
230 |
231 | # Select the correct model to train
232 | if model_type == "lightgbm":
233 | model = train_lightgbm(X_train, X_val, y_train, y_val, task_type)
234 | elif model_type == "xgboost":
235 | model = train_xgboost(X_train, X_val, y_train, y_val, task_type)
236 | elif model_type == "catboost":
237 | model = train_catboost(X_train, X_val, y_train, y_val, task_type)
238 | else:
239 | raise ValueError("Unsupported model type")
240 |
241 | # Call the score_features function for the correct task (regression, binary, multiclass)
242 | selected_features_df = shap_select(model, X_val, y_val, task=task_type)
243 |
244 | # Check feature significance for all task types
245 | selected_rows = selected_features_df[
246 | selected_features_df["feature name"].isin(["x7", "x8", "x9"])
247 | ]
248 | assert (
249 | selected_rows["selected"] <= 0
250 | ).all(), (
251 | "The Selected column must have negative or zero values for features x7, x8, x9"
252 | )
253 |
254 | other_features_rows = selected_features_df[
255 | ~selected_features_df["feature name"].isin(["x7", "x8", "x9", "const"])
256 | ]
257 | assert (
258 | other_features_rows["selected"] > 0
259 | ).all(), "The Selected column must have positive values for features other than x7, x8, x9"
--------------------------------------------------------------------------------
/tests/test_shap_feature_generation.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | import pandas as pd
3 | import numpy as np
4 | from shap_select.select import create_shap_features
5 | import lightgbm as lgb
6 |
7 |
8 | @pytest.fixture
9 | def sample_data_binary():
10 | """Generate sample data for binary classification."""
11 | np.random.seed(42)
12 | X = pd.DataFrame(np.random.normal(size=(100, 5)), columns=[f"x{i}" for i in range(5)])
13 | y = (X["x0"] > 0).astype(int)
14 | return X, y
15 |
16 |
17 | @pytest.fixture
18 | def sample_data_multiclass():
19 | """Generate sample data for multiclass classification."""
20 | np.random.seed(42)
21 | X = pd.DataFrame(np.random.normal(size=(100, 5)), columns=[f"x{i}" for i in range(5)])
22 | y = np.random.choice([0, 1, 2], size=100)
23 | return X, y
24 |
25 |
26 | def test_shap_feature_generation_binary(sample_data_binary):
27 | """Test SHAP feature generation for binary classification."""
28 | X, y = sample_data_binary
29 |
30 | model = lgb.LGBMClassifier()
31 | model.fit(X, y)
32 |
33 | shap_df = create_shap_features(model, X)
34 | assert isinstance(shap_df, pd.DataFrame), "SHAP output should be a DataFrame"
35 | assert shap_df.shape == X.shape, "SHAP output shape should match input data"
36 | assert shap_df.isnull().sum().sum() == 0, "No missing values expected in SHAP output"
37 |
38 |
39 | def test_shap_feature_generation_multiclass(sample_data_multiclass):
40 | """Test SHAP feature generation for multiclass classification."""
41 | X, y = sample_data_multiclass
42 |
43 | model = lgb.LGBMClassifier(objective="multiclass", num_class=3)
44 | model.fit(X, y)
45 |
46 | shap_df = create_shap_features(model, X, classes=[0, 1, 2])
47 | assert isinstance(shap_df, dict), "SHAP output should be a dictionary for multiclass"
48 | assert all(isinstance(v, pd.DataFrame) for v in shap_df.values()), "Each class should have a DataFrame"
49 | assert shap_df[0].shape == X.shape, "SHAP output shape should match input data for each class"
50 |
--------------------------------------------------------------------------------
/tests/test_significance_calculation.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | import pandas as pd
3 | import numpy as np
4 | from shap_select.select import binary_classifier_significance, regression_significance
5 | import statsmodels.api as sm
6 |
7 |
8 | @pytest.fixture
9 | def shap_features_binary():
10 | """Generate sample SHAP values for binary classification."""
11 | np.random.seed(42)
12 | return pd.DataFrame(np.random.normal(size=(100, 5)), columns=[f"x{i}" for i in range(5)])
13 |
14 |
15 | @pytest.fixture
16 | def binary_target():
17 | """Generate binary target."""
18 | np.random.seed(42)
19 | return pd.Series(np.random.choice([0, 1], size=100))
20 |
21 |
22 | def test_binary_classifier_significance(shap_features_binary, binary_target):
23 | """Test significance calculation for binary classification."""
24 | result_df = binary_classifier_significance(shap_features_binary, binary_target, alpha=1e-4)
25 |
26 | assert "feature name" in result_df.columns, "Result should contain feature names"
27 | assert "coefficient" in result_df.columns, "Result should contain coefficients"
28 | assert "stat.significance" in result_df.columns, "Result should contain statistical significance"
29 | assert result_df.shape[0] == shap_features_binary.shape[1], "Each feature should have a row in the output"
30 | assert (result_df["stat.significance"] > 0).all(), "All p-values should be non-negative"
31 |
32 |
33 | @pytest.fixture
34 | def shap_features_regression():
35 | """Generate sample SHAP values for regression."""
36 | np.random.seed(42)
37 | return pd.DataFrame(np.random.normal(size=(100, 5)), columns=[f"x{i}" for i in range(5)])
38 |
39 |
40 | @pytest.fixture
41 | def regression_target():
42 | """Generate regression target."""
43 | np.random.seed(42)
44 | return pd.Series(np.random.normal(size=100))
45 |
46 |
47 | def test_regression_significance(shap_features_regression, regression_target):
48 | """Test significance calculation for regression."""
49 | result_df = regression_significance(shap_features_regression, regression_target, alpha=1e-6)
50 |
51 | assert "feature name" in result_df.columns, "Result should contain feature names"
52 | assert "coefficient" in result_df.columns, "Result should contain coefficients"
53 | assert "stat.significance" in result_df.columns, "Result should contain statistical significance"
54 | assert result_df.shape[0] == shap_features_regression.shape[1], "Each feature should have a row in the output"
55 | assert (result_df["stat.significance"] > 0).all(), "All p-values should be non-negative"
56 |
--------------------------------------------------------------------------------