lime-ndt 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. lime_ndt-0.1.0/LICENSE +233 -0
  2. lime_ndt-0.1.0/PKG-INFO +90 -0
  3. lime_ndt-0.1.0/README.md +76 -0
  4. lime_ndt-0.1.0/lime_ndt/RTF/DT_extraction.py +174 -0
  5. lime_ndt-0.1.0/lime_ndt/RTF/__init__.py +0 -0
  6. lime_ndt-0.1.0/lime_ndt/RTF/forest/DT_grouping.py +528 -0
  7. lime_ndt-0.1.0/lime_ndt/RTF/forest/Forest.py +156 -0
  8. lime_ndt-0.1.0/lime_ndt/RTF/forest/Subforest.py +150 -0
  9. lime_ndt-0.1.0/lime_ndt/RTF/forest/__init__.py +0 -0
  10. lime_ndt-0.1.0/lime_ndt/RTF/forest/common.py +51 -0
  11. lime_ndt-0.1.0/lime_ndt/RTF/nrf/Neural_Decision_Tree.py +1030 -0
  12. lime_ndt-0.1.0/lime_ndt/RTF/nrf/Neural_Random_Forest.py +598 -0
  13. lime_ndt-0.1.0/lime_ndt/RTF/nrf/__init__.py +0 -0
  14. lime_ndt-0.1.0/lime_ndt/RTF/nrf/test.py +114 -0
  15. lime_ndt-0.1.0/lime_ndt/RTF/nrf/test2.py +48 -0
  16. lime_ndt-0.1.0/lime_ndt/RTF/nrf/test3.py +52 -0
  17. lime_ndt-0.1.0/lime_ndt/RTF/utils/__init__.py +0 -0
  18. lime_ndt-0.1.0/lime_ndt/RTF/utils/common_functions.py +344 -0
  19. lime_ndt-0.1.0/lime_ndt/RTF/utils/comparison_functions.py +234 -0
  20. lime_ndt-0.1.0/lime_ndt/__init__.py +0 -0
  21. lime_ndt-0.1.0/lime_ndt/discretize.py +232 -0
  22. lime_ndt-0.1.0/lime_ndt/explanation.py +324 -0
  23. lime_ndt-0.1.0/lime_ndt/lime_base.py +205 -0
  24. lime_ndt-0.1.0/lime_ndt/lime_tabular.py +721 -0
  25. lime_ndt-0.1.0/lime_ndt/submodular_pick.py +128 -0
  26. lime_ndt-0.1.0/lime_ndt/tests/__init__.py +0 -0
  27. lime_ndt-0.1.0/lime_ndt/tests/test_discretize.py +179 -0
  28. lime_ndt-0.1.0/lime_ndt/tests/test_generic_utils.py +95 -0
  29. lime_ndt-0.1.0/lime_ndt/tests/test_lime_tabular.py +644 -0
  30. lime_ndt-0.1.0/lime_ndt/utils/__init__.py +0 -0
  31. lime_ndt-0.1.0/lime_ndt/utils/generic_utils.py +39 -0
  32. lime_ndt-0.1.0/lime_ndt/utils/ndt_sklearn_wrapper.py +39 -0
  33. lime_ndt-0.1.0/lime_ndt/wrappers/__init__.py +0 -0
  34. lime_ndt-0.1.0/lime_ndt/wrappers/scikit_image.py +114 -0
  35. lime_ndt-0.1.0/lime_ndt.egg-info/PKG-INFO +90 -0
  36. lime_ndt-0.1.0/lime_ndt.egg-info/SOURCES.txt +39 -0
  37. lime_ndt-0.1.0/lime_ndt.egg-info/dependency_links.txt +1 -0
  38. lime_ndt-0.1.0/lime_ndt.egg-info/requires.txt +6 -0
  39. lime_ndt-0.1.0/lime_ndt.egg-info/top_level.txt +1 -0
  40. lime_ndt-0.1.0/setup.cfg +4 -0
  41. lime_ndt-0.1.0/setup.py +27 -0
lime_ndt-0.1.0/LICENSE ADDED
@@ -0,0 +1,233 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+
9
+ 1. Definitions.
10
+
11
+
12
+ "License" shall mean the terms and conditions for use, reproduction,
13
+ and distribution as defined by Sections 1 through 9 of this document.
14
+
15
+
16
+ "Licensor" shall mean the copyright owner or entity authorized by
17
+ the copyright owner that is granting the License.
18
+
19
+
20
+ "Legal Entity" shall mean the union of the acting entity and all
21
+ other entities that control, are controlled by, or are under common
22
+ control with that entity. For the purposes of this definition,
23
+ "control" means (i) the power, direct or indirect, to cause the
24
+ direction or management of such entity, whether by contract or
25
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
26
+ outstanding shares, or (iii) beneficial ownership of such entity.
27
+
28
+
29
+ "You" (or "Your") shall mean an individual or Legal Entity
30
+ exercising permissions granted by this License.
31
+
32
+
33
+ "Source" form shall mean the preferred form for making modifications,
34
+ including but not limited to software source code, documentation
35
+ source, and configuration files.
36
+
37
+
38
+ "Object" form shall mean any form resulting from mechanical
39
+ transformation or translation of a Source form, including but
40
+ not limited to compiled object code, generated documentation,
41
+ and conversions to other media types.
42
+
43
+
44
+ "Work" shall mean the work of authorship, whether in Source or
45
+ Object form, made available under the License, as indicated by a
46
+ copyright notice that is included in or attached to the work
47
+ (an example is provided in the Appendix below).
48
+
49
+
50
+ "Derivative Works" shall mean any work, whether in Source or Object
51
+ form, that is based on (or derived from) the Work and for which the
52
+ editorial revisions, annotations, elaborations, or other modifications
53
+ represent, as a whole, an original work of authorship. For the purposes
54
+ of this License, Derivative Works shall not include works that remain
55
+ separable from, or merely link (or bind by name) to the interfaces of,
56
+ the Work and Derivative Works thereof.
57
+
58
+
59
+ "Contribution" shall mean any work of authorship, including
60
+ the original version of the Work and any modifications or additions
61
+ to that Work or Derivative Works thereof, that is intentionally
62
+ submitted to Licensor for inclusion in the Work by the copyright owner
63
+ or by an individual or Legal Entity authorized to submit on behalf of
64
+ the copyright owner. For the purposes of this definition, "submitted"
65
+ means any form of electronic, verbal, or written communication sent
66
+ to the Licensor or its representatives, including but not limited to
67
+ communication on electronic mailing lists, source code control systems,
68
+ and issue tracking systems that are managed by, or on behalf of, the
69
+ Licensor for the purpose of discussing and improving the Work, but
70
+ excluding communication that is conspicuously marked or otherwise
71
+ designated in writing by the copyright owner as "Not a Contribution."
72
+
73
+
74
+ "Contributor" shall mean Licensor and any individual or Legal Entity
75
+ on behalf of whom a Contribution has been received by Licensor and
76
+ subsequently incorporated within the Work.
77
+
78
+
79
+ 2. Grant of Copyright License. Subject to the terms and conditions of
80
+ this License, each Contributor hereby grants to You a perpetual,
81
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
82
+ copyright license to reproduce, prepare Derivative Works of,
83
+ publicly display, publicly perform, sublicense, and distribute the
84
+ Work and such Derivative Works in Source or Object form.
85
+
86
+
87
+ 3. Grant of Patent License. Subject to the terms and conditions of
88
+ this License, each Contributor hereby grants to You a perpetual,
89
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
90
+ (except as stated in this section) patent license to make, have made,
91
+ use, offer to sell, sell, import, and otherwise transfer the Work,
92
+ where such license applies only to those patent claims licensable
93
+ by such Contributor that are necessarily infringed by their
94
+ Contribution(s) alone or by combination of their Contribution(s)
95
+ with the Work to which such Contribution(s) was submitted. If You
96
+ institute patent litigation against any entity (including a
97
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
98
+ or a Contribution incorporated within the Work constitutes direct
99
+ or contributory patent infringement, then any patent licenses
100
+ granted to You under this License for that Work shall terminate
101
+ as of the date such litigation is filed.
102
+
103
+
104
+ 4. Redistribution. You may reproduce and distribute copies of the
105
+ Work or Derivative Works thereof in any medium, with or without
106
+ modifications, and in Source or Object form, provided that You
107
+ meet the following conditions:
108
+
109
+
110
+ (a) You must give any other recipients of the Work or
111
+ Derivative Works a copy of this License; and
112
+
113
+
114
+ (b) You must cause any modified files to carry prominent notices
115
+ stating that You changed the files; and
116
+
117
+
118
+ (c) You must retain, in the Source form of any Derivative Works
119
+ that You distribute, all copyright, patent, trademark, and
120
+ attribution notices from the Source form of the Work,
121
+ excluding those notices that do not pertain to any part of
122
+ the Derivative Works; and
123
+
124
+
125
+ (d) If the Work includes a "NOTICE" text file as part of its
126
+ distribution, then any Derivative Works that You distribute must
127
+ include a readable copy of the attribution notices contained
128
+ within such NOTICE file, excluding those notices that do not
129
+ pertain to any part of the Derivative Works, in at least one
130
+ of the following places: within a NOTICE text file distributed
131
+ as part of the Derivative Works; within the Source form or
132
+ documentation, if provided along with the Derivative Works; or,
133
+ within a display generated by the Derivative Works, if and
134
+ wherever such third-party notices normally appear. The contents
135
+ of the NOTICE file are for informational purposes only and
136
+ do not modify the License. You may add Your own attribution
137
+ notices within Derivative Works that You distribute, alongside
138
+ or as an addendum to the NOTICE text from the Work, provided
139
+ that such additional attribution notices cannot be construed
140
+ as modifying the License.
141
+
142
+
143
+ You may add Your own copyright statement to Your modifications and
144
+ may provide additional or different license terms and conditions
145
+ for use, reproduction, or distribution of Your modifications, or
146
+ for any such Derivative Works as a whole, provided Your use,
147
+ reproduction, and distribution of the Work otherwise complies with
148
+ the conditions stated in this License.
149
+
150
+
151
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
152
+ any Contribution intentionally submitted for inclusion in the Work
153
+ by You to the Licensor shall be under the terms and conditions of
154
+ this License, without any additional terms or conditions.
155
+ Notwithstanding the above, nothing herein shall supersede or modify
156
+ the terms of any separate license agreement you may have executed
157
+ with Licensor regarding such Contributions.
158
+
159
+
160
+ 6. Trademarks. This License does not grant permission to use the trade
161
+ names, trademarks, service marks, or product names of the Licensor,
162
+ except as required for reasonable and customary use in describing the
163
+ origin of the Work and reproducing the content of the NOTICE file.
164
+
165
+
166
+ 7. Disclaimer of Warranty. Unless required by applicable law or
167
+ agreed to in writing, Licensor provides the Work (and each
168
+ Contributor provides its Contributions) on an "AS IS" BASIS,
169
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
170
+ implied, including, without limitation, any warranties or conditions
171
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
172
+ PARTICULAR PURPOSE. You are solely responsible for determining the
173
+ appropriateness of using or redistributing the Work and assume any
174
+ risks associated with Your exercise of permissions under this License.
175
+
176
+
177
+ 8. Limitation of Liability. In no event and under no legal theory,
178
+ whether in tort (including negligence), contract, or otherwise,
179
+ unless required by applicable law (such as deliberate and grossly
180
+ negligent acts) or agreed to in writing, shall any Contributor be
181
+ liable to You for damages, including any direct, indirect, special,
182
+ incidental, or consequential damages of any character arising as a
183
+ result of this License or out of the use or inability to use the
184
+ Work (including but not limited to damages for loss of goodwill,
185
+ work stoppage, computer failure or malfunction, or any and all
186
+ other commercial damages or losses), even if such Contributor
187
+ has been advised of the possibility of such damages.
188
+
189
+
190
+ 9. Accepting Warranty or Additional Liability. While redistributing
191
+ the Work or Derivative Works thereof, You may choose to offer,
192
+ and charge a fee for, acceptance of support, warranty, indemnity,
193
+ or other liability obligations and/or rights consistent with this
194
+ License. However, in accepting such obligations, You may act only
195
+ on Your own behalf and on Your sole responsibility, not on behalf
196
+ of any other Contributor, and only if You agree to indemnify,
197
+ defend, and hold each Contributor harmless for any liability
198
+ incurred by, or claims asserted against, such Contributor by reason
199
+ of your accepting any such warranty or additional liability.
200
+
201
+
202
+ END OF TERMS AND CONDITIONS
203
+
204
+
205
+ APPENDIX: How to apply the Apache License to your work.
206
+
207
+
208
+ To apply the Apache License to your work, attach the following
209
+ boilerplate notice, with the fields enclosed by brackets "[]"
210
+ replaced with your own identifying information. (Don't include
211
+ the brackets!) The text should be enclosed in the appropriate
212
+ comment syntax for the file format. We also recommend that a
213
+ file or class name and description of purpose be included on the
214
+ same "printed page" as the copyright notice for easier
215
+ identification within third-party archives.
216
+
217
+
218
+ Copyright 2024 [name of copyright owner]
219
+
220
+
221
+ Licensed under the Apache License, Version 2.0 (the "License");
222
+ you may not use this file except in compliance with the License.
223
+ You may obtain a copy of the License at
224
+
225
+
226
+ http://www.apache.org/licenses/LICENSE-2.0
227
+
228
+
229
+ Unless required by applicable law or agreed to in writing, software
230
+ distributed under the License is distributed on an "AS IS" BASIS,
231
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
232
+ See the License for the specific language governing permissions and
233
+ limitations under the License.
@@ -0,0 +1,90 @@
1
+ Metadata-Version: 2.1
2
+ Name: lime_ndt
3
+ Version: 0.1.0
4
+ Summary: Enhancing LIME through Neural Decision Trees
5
+ Home-page: https://github.com/aymen20002005/lime_ndt/tree/main
6
+ Author: Mohamed Aymen BOUYAHIA
7
+ Author-email: mohamed-aymen.bouyahia@ensta-paris.fr
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.7
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+
15
+ # lime_ndt
16
+
17
+ lime_ndt is a Python library that introduces an enhanced version of the LIME technique for model explainability, leveraging Neural Decision Trees (NDTs) for improved local and global interpretability of machine learning models.
18
+
19
+ ## Features
20
+
21
+ - Enhanced LIME explanations using Neural Decision Trees.
22
+ - Support for tabular data.
23
+ - Tools for extracting, analyzing, and comparing decision trees and forests.
24
+ - Utilities for submodular pick and discretization.
25
+ - Integration with Keras and scikit-learn.
26
+
27
+ ## Example Usage
28
+
29
+ Below is a minimal example showing how to use lime_ndt to explain a regression model on the diabetes dataset:
30
+
31
+ ```python
32
+ from sklearn.datasets import load_diabetes
33
+ from sklearn.model_selection import train_test_split
34
+ from sklearn.ensemble import RandomForestRegressor
35
+ from lime_ndt.lime_tabular import LimeTabularExplainer
36
+ from lime_ndt.utils.ndt_sklearn_wrapper import NDTRegressorWrapper
37
+ import matplotlib.pyplot as plt
38
+
39
+ # Load the diabetes dataset
40
+ diabetes = load_diabetes()
41
+ X = diabetes.data
42
+ y = diabetes.target
43
+
44
+ # Split into train/test sets
45
+ X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
46
+
47
+ # Train a Random Forest regressor
48
+ rf = RandomForestRegressor(random_state=42)
49
+ rf.fit(X_train, y_train)
50
+
51
+ # Prediction function
52
+ def predict_fn(X):
53
+ return rf.predict(X)
54
+
55
+ # Create the LIME explainer
56
+ explainer = LimeTabularExplainer(
57
+ X_train,
58
+ feature_names=diabetes.feature_names,
59
+ class_names=None,
60
+ discretize_continuous=True,
61
+ mode='regression',
62
+ )
63
+
64
+ # Create the local NDT model
65
+ model_regressor = NDTRegressorWrapper(gammas=[1,1], D=X_train.shape[1], max_depth=4)
66
+
67
+ # Explain a test instance
68
+ exp = explainer.explain_instance(
69
+ X_test[0],
70
+ predict_fn,
71
+ num_features=10,
72
+ model_regressor=model_regressor
73
+ )
74
+
75
+ # Visualize the explanation
76
+ exp.as_pyplot_figure()
77
+ plt.show()
78
+ ```
79
+ ![image](https://github.com/user-attachments/assets/fbdf4b6e-8c4c-4016-998a-aa71e29e05d9)
80
+
81
+ ## Requirements
82
+
83
+ - Python 3.7+
84
+ - numpy, pandas, scikit-learn, keras, tensorflow, matplotlib
85
+
86
+ See [requirements.txt](requirements.txt) for the full list.
87
+
88
+ ## License
89
+
90
+ This project is licensed under the Apache License 2.0. See the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,76 @@
1
+ # lime_ndt
2
+
3
+ lime_ndt is a Python library that introduces an enhanced version of the LIME technique for model explainability, leveraging Neural Decision Trees (NDTs) for improved local and global interpretability of machine learning models.
4
+
5
+ ## Features
6
+
7
+ - Enhanced LIME explanations using Neural Decision Trees.
8
+ - Support for tabular data.
9
+ - Tools for extracting, analyzing, and comparing decision trees and forests.
10
+ - Utilities for submodular pick and discretization.
11
+ - Integration with Keras and scikit-learn.
12
+
13
+ ## Example Usage
14
+
15
+ Below is a minimal example showing how to use lime_ndt to explain a regression model on the diabetes dataset:
16
+
17
+ ```python
18
+ from sklearn.datasets import load_diabetes
19
+ from sklearn.model_selection import train_test_split
20
+ from sklearn.ensemble import RandomForestRegressor
21
+ from lime_ndt.lime_tabular import LimeTabularExplainer
22
+ from lime_ndt.utils.ndt_sklearn_wrapper import NDTRegressorWrapper
23
+ import matplotlib.pyplot as plt
24
+
25
+ # Load the diabetes dataset
26
+ diabetes = load_diabetes()
27
+ X = diabetes.data
28
+ y = diabetes.target
29
+
30
+ # Split into train/test sets
31
+ X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
32
+
33
+ # Train a Random Forest regressor
34
+ rf = RandomForestRegressor(random_state=42)
35
+ rf.fit(X_train, y_train)
36
+
37
+ # Prediction function
38
+ def predict_fn(X):
39
+ return rf.predict(X)
40
+
41
+ # Create the LIME explainer
42
+ explainer = LimeTabularExplainer(
43
+ X_train,
44
+ feature_names=diabetes.feature_names,
45
+ class_names=None,
46
+ discretize_continuous=True,
47
+ mode='regression',
48
+ )
49
+
50
+ # Create the local NDT model
51
+ model_regressor = NDTRegressorWrapper(gammas=[1,1], D=X_train.shape[1], max_depth=4)
52
+
53
+ # Explain a test instance
54
+ exp = explainer.explain_instance(
55
+ X_test[0],
56
+ predict_fn,
57
+ num_features=10,
58
+ model_regressor=model_regressor
59
+ )
60
+
61
+ # Visualize the explanation
62
+ exp.as_pyplot_figure()
63
+ plt.show()
64
+ ```
65
+ ![image](https://github.com/user-attachments/assets/fbdf4b6e-8c4c-4016-998a-aa71e29e05d9)
66
+
67
+ ## Requirements
68
+
69
+ - Python 3.7+
70
+ - numpy, pandas, scikit-learn, keras, tensorflow, matplotlib
71
+
72
+ See [requirements.txt](requirements.txt) for the full list.
73
+
74
+ ## License
75
+
76
+ This project is licensed under the Apache License 2.0. See the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,174 @@
1
+ import numpy as np
2
+ from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
3
+ from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
4
+
5
+
6
+ def generateNewDataClassification(oracle, X, y, ratio, replace_labels=False, by_class=True, **params):
7
+ '''
8
+ Generate new data using an oracle to label randomly generated examples.
9
+ The quantity of new data depends on the input ratio
10
+ '''
11
+
12
+ newX = np.copy(X)
13
+ classes = np.unique(y)
14
+
15
+ if hasattr(oracle, "predict_classes"):
16
+ predict_func = oracle.predict_classes
17
+ else:
18
+ predict_func = oracle.predict
19
+
20
+ if replace_labels:
21
+ newY = predict_func(X, **params)
22
+ if not isinstance(newY, list):
23
+ newY = np.reshape(newY, (newY.shape[0],))
24
+
25
+ else:
26
+ newY = np.copy(y)
27
+
28
+ if ratio > 0:
29
+
30
+ if by_class: #### distinguish between classes when sampling values for new examples
31
+
32
+ for c in classes:
33
+ idx = np.nonzero(y == c)[0]
34
+ X_cl = X[idx, :]
35
+
36
+ size = np.ceil(ratio*X_cl.shape[0]).astype(int) ### at least one example from each class
37
+
38
+ extra_X = np.zeros((size, X_cl.shape[1]))
39
+
40
+ idx = np.random.choice(X_cl.shape[0], size=extra_X.shape,
41
+ replace=True)
42
+
43
+ extra_X = X_cl[idx, np.arange(X_cl.shape[1])[None, :]]
44
+
45
+ newX = np.vstack((newX, extra_X))
46
+ # print(predict_func)
47
+ preds = predict_func(extra_X, **params)
48
+ if not isinstance(preds, list):
49
+ if len(preds.shape) > 1:
50
+ if preds.shape[1] == 1:
51
+ preds = preds.reshape((preds.shape[0],))
52
+ # print(preds.shape)
53
+ newY = np.concatenate((newY, preds)) ### generate labels for
54
+ ### the new examples
55
+ else:
56
+ newY = np.concatenate((newY, preds))
57
+
58
+ else:
59
+
60
+ size = np.ceil(ratio*X.shape[0]).astype(int) ### at least one example from each class
61
+
62
+ extra_X = np.zeros((size, X.shape[1]))
63
+
64
+ idx = np.random.choice(X.shape[0], size=extra_X.shape, replace=True)
65
+
66
+ extra_X = X[idx, np.arange(X.shape[1])[None, :]]
67
+
68
+ newX = np.vstack((newX, extra_X))
69
+ preds = predict_func(extra_X, **params)
70
+ preds = np.reshape(preds, (preds.shape[0],))
71
+ newY = np.concatenate((newY, preds)) ### generate labels for
72
+ ### the new examples
73
+
74
+ classes_Ynew = np.unique(newY)
75
+ not_represented = set(classes) - set(classes_Ynew)
76
+
77
+ if bool(not_represented):
78
+ for c in not_represented:
79
+ idx = np.nonzero(y == c)[0]
80
+ # rand_idx = np.random.choice(idx, size=1)
81
+
82
+ newX = np.vstack((newX, X[idx, :]))
83
+ newY = np.concatenate((newY, y[idx]))
84
+
85
+ idx = np.arange(len(newY))
86
+ np.random.shuffle(idx) ### shuffle examples
87
+ newX = newX[idx, :]
88
+ newY = np.array([newY[i] for i in idx])
89
+
90
+ # print("#################")
91
+ # print(idx)
92
+ # print(newX.shape)
93
+ # print(len(newY))
94
+
95
+ return(newX, newY)
96
+
97
+
98
+ def generateNewDataRegression(oracle, X, y, ratio, replace_labels=False, by_class=None, **params):
99
+ '''
100
+ Generate new data using an oracle to label randomly generated examples.
101
+ The quantity of new data depends on the input ratio
102
+ '''
103
+
104
+ newX = np.copy(X)
105
+
106
+ if replace_labels:
107
+ newY = oracle.predict(X, **params)
108
+ newY = np.reshape(newY, (newY.shape[0],))
109
+
110
+ else:
111
+ newY = np.copy(y)
112
+
113
+ if ratio > 0:
114
+
115
+ size = np.ceil(ratio*X.shape[0]).astype(int) ### at least one example from each class
116
+
117
+ extra_X = np.zeros((size, X.shape[1]))
118
+
119
+ idx = np.random.choice(X.shape[0], size=extra_X.shape, replace=True)
120
+
121
+ extra_X = X[idx, np.arange(X.shape[1])[None, :]]
122
+
123
+ newX = np.vstack((newX, extra_X))
124
+
125
+ preds = oracle.predict(extra_X, **params)
126
+ preds = np.reshape(preds, (preds.shape[0],))
127
+ newY = np.concatenate((newY, preds)) ### generate labels for
128
+ ### the new examples
129
+
130
+ idx = np.arange(len(newY))
131
+ np.random.shuffle(idx) ### shuffle examples
132
+ newX = newX[idx, :]
133
+ newY = newY[idx]
134
+
135
+ return(newX, newY)
136
+
137
+
138
+ def DT_extraction(oracle, X, Y, ratio, max_depth, n_trees=1,
139
+ replace_labels=False, by_class=True,
140
+ classification=True, **params):
141
+
142
+ if hasattr(oracle, "_estimator_type"):
143
+ if oracle._estimator_type == "classifier":
144
+ generateNewData = generateNewDataClassification
145
+ DecisionTree = DecisionTreeClassifier
146
+ RandomForest = RandomForestClassifier
147
+ else:
148
+ generateNewData = generateNewDataRegression
149
+ DecisionTree = DecisionTreeRegressor
150
+ RandomForest = RandomForestRegressor
151
+
152
+ else:
153
+ if classification:
154
+ generateNewData = generateNewDataClassification
155
+ DecisionTree = DecisionTreeClassifier
156
+ RandomForest = RandomForestClassifier
157
+ else:
158
+ generateNewData = generateNewDataRegression
159
+ DecisionTree = DecisionTreeRegressor
160
+ RandomForest = RandomForestRegressor
161
+
162
+ newX, newY = generateNewData(oracle, X, Y, ratio, replace_labels, by_class, **params)
163
+
164
+ if n_trees == 1:
165
+ tree = DecisionTree(max_depth=max_depth, random_state=0)
166
+ tree.fit(newX, newY)
167
+
168
+ return tree
169
+
170
+ else:
171
+ trees = RandomForest(n_estimators=n_trees, max_depth=max_depth, random_state=0)
172
+ trees.fit(newX, newY)
173
+
174
+ return trees
File without changes