pytofi 0.0.1__py3-none-any.whl
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.
- pytofi-0.0.1.dist-info/METADATA +51 -0
- pytofi-0.0.1.dist-info/RECORD +9 -0
- pytofi-0.0.1.dist-info/WHEEL +5 -0
- pytofi-0.0.1.dist-info/licenses/LICENSE +21 -0
- pytofi-0.0.1.dist-info/top_level.txt +1 -0
- tofi/__init__.py +6 -0
- tofi/crosser.py +490 -0
- tofi/inferer.py +984 -0
- tofi/utils.py +47 -0
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pytofi
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Tests on Feature Importance
|
|
5
|
+
Author-email: Po-Hsien Huang <psyphh@nccu.edu.tw>
|
|
6
|
+
Classifier: Programming Language :: Python :: 3
|
|
7
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
8
|
+
Classifier: Operating System :: OS Independent
|
|
9
|
+
Requires-Python: >=3.9
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: scikit-learn>=1.5.0
|
|
13
|
+
Requires-Dist: pandas>=2.0.3
|
|
14
|
+
Dynamic: license-file
|
|
15
|
+
|
|
16
|
+
# TOFI: Tests on Feature Importance
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
## Overview
|
|
20
|
+
|
|
21
|
+
`tofi` is a python package for conducting tests on feature importance in machine learning. It is written on the basis of [`scikit-learn`](https://scikit-learn.org/stable/index.html). Hence, in principle, any regressor/classifier learned by `scikit-learn` can be inferred by `tofi`.
|
|
22
|
+
|
|
23
|
+
`tofi` provides two types of `Inferer` for making inferences: `CIT` for conditional independence test and `RIT` for risk invariance test. `CIT` can implement the holdout randomization test (HRT; Tansey et al., 2022), residual permutation test (RPT; Huang, 2024), and conditional predictive impact (CPI; Watson & Wright, 2021). On the other hand, `RIT` can conduct leave-one-covariate-out (LOCO; Lei et al., 2018) and plug-in estimation (PIE; Williamson et al., 2023). In addition, `tofi` also constructs a `Crosser` class. With the help of `Crosser`, cross-fitting and $p$-value combination can be easily implemented to improve the stability and even statistical power of the CITs and RITs.
|
|
24
|
+
|
|
25
|
+
## Installation
|
|
26
|
+
`tofi` can be installed via `pip`:
|
|
27
|
+
```
|
|
28
|
+
pip install pytofi
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Tutorial
|
|
32
|
+
|
|
33
|
+
Three Jupyter notebooks are available to learn the use of `sial`:
|
|
34
|
+
|
|
35
|
+
1. [Conditional Independence Tests](https://github.com/aipsylab/tofi/blob/main/tutorial/tutorial_1_cit.ipynb)
|
|
36
|
+
2. [Risk Invariance Tests](https://github.com/aipsylab/tofi/blob/main/tutorial/tutorial_2_rit.ipynb)
|
|
37
|
+
3. [Cross-Fitting and $p$-Value Combination](https://github.com/aipsylab/tofi/blob/main/tutorial/tutorial_3_crosser.ipynb)
|
|
38
|
+
|
|
39
|
+
These notebooks assume that readers have experiences in using `scikit-learn`.
|
|
40
|
+
|
|
41
|
+
## References
|
|
42
|
+
|
|
43
|
+
Huang, P.-H. (2024). Residual Permutation Tests for Feature Importance in Machine Learning. [Manuscript submitted for publication].
|
|
44
|
+
|
|
45
|
+
Lei, J., G’Sell, M., Rinaldo, A., Tibshirani, R. J., & Wasserman, L. (2018). Distribution-free predictive inference for regression. Journal of the American Statistical Association, 113(523), 1094–1111. doi: 10.1080/01621459.2017.1307116
|
|
46
|
+
|
|
47
|
+
Tansey, W., Veitch, V., Zhang, H., Rabadan, R., & Blei, D. M. (2022). The holdout randomization test for feature selection in black box models. Journal of Computational and Graphical Statistics, 31(1), 151–162. doi: 10.1080/10618600.2021.1923520
|
|
48
|
+
|
|
49
|
+
Watson, D., & Wright, M. (2021). Testing conditional independence in supervised learning algorithms. Machine Learning, 110, 1-23. doi: 10.1007/s10994-021-06030-6
|
|
50
|
+
|
|
51
|
+
Williamson, B. D., Gilbert, P. B., Simon, N. R., & Carone, M. (2023). A general framework for inference on algorithm-agnostic variable importance. Journal of the American Statistical Association, 118(543), 1645–1658. doi: 10.1080/01621459.2021.2003200
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
pytofi-0.0.1.dist-info/licenses/LICENSE,sha256=rTKytVFyxeiVubTaX35pqcq2whSZYxCD5mOelzBflME,1065
|
|
2
|
+
tofi/__init__.py,sha256=-5hbxVx7RtokIXa3BsPje_80GXjhpW-_DQKQb5ccLBU,118
|
|
3
|
+
tofi/crosser.py,sha256=eD2xLHGRnsZrKF0LR0WH2PvNHLawobvsT4zjz9usGVQ,15459
|
|
4
|
+
tofi/inferer.py,sha256=nUHPsTmxrmBd_FGKB88i39o_v47105Hr1s5CeBrHjOM,37128
|
|
5
|
+
tofi/utils.py,sha256=A4mg6vu-VWUqrfEYsjSfZruM7tRwNYB2mzs1ZQV3Rvw,1453
|
|
6
|
+
pytofi-0.0.1.dist-info/METADATA,sha256=4XdZOpZXFrYo5BbbdSFKdzPQcYv-jTPp3UXz3_lHYEA,3111
|
|
7
|
+
pytofi-0.0.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
8
|
+
pytofi-0.0.1.dist-info/top_level.txt,sha256=8s92NUTG5IVmFjb8EXdb0TCiLrPPflcgpwq7dr58_pI,5
|
|
9
|
+
pytofi-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 aipsylab
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
tofi
|
tofi/__init__.py
ADDED
tofi/crosser.py
ADDED
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
import math
|
|
2
|
+
import scipy
|
|
3
|
+
import warnings
|
|
4
|
+
import numpy as np
|
|
5
|
+
import pandas as pd
|
|
6
|
+
from sklearn.base import clone
|
|
7
|
+
from sklearn import model_selection
|
|
8
|
+
from sklearn.base import is_classifier
|
|
9
|
+
from sklearn.utils.validation import check_is_fitted
|
|
10
|
+
from sklearn.preprocessing import LabelBinarizer
|
|
11
|
+
from sklearn.metrics import get_scorer, get_scorer_names
|
|
12
|
+
from .utils import _sample
|
|
13
|
+
|
|
14
|
+
class Crosser():
|
|
15
|
+
"""
|
|
16
|
+
An object for repeated cross-fitting
|
|
17
|
+
|
|
18
|
+
Parameters
|
|
19
|
+
----------
|
|
20
|
+
estimator : estimator object
|
|
21
|
+
The base estimator for repeated cross-fitting.
|
|
22
|
+
|
|
23
|
+
cv : cross-validation generator
|
|
24
|
+
The cross-validation generator for repeated cross-fitting.
|
|
25
|
+
It must be a class member of `KFold`, `RepeatedKFold`,
|
|
26
|
+
`ShuffleSplit`, `StratifiedShuffleSplit`.
|
|
27
|
+
|
|
28
|
+
scoring : str or callable, default=None
|
|
29
|
+
Strategy to evaluate the performance of the cross-validated
|
|
30
|
+
model when using `summarize`. To see availble scoring methods
|
|
31
|
+
via `str`, use `sklearn.get_scorer_names()`.
|
|
32
|
+
|
|
33
|
+
- For regression tasks, `None` means "r2".
|
|
34
|
+
- For classification tasks, `None` means "accuracy".
|
|
35
|
+
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
estimator,
|
|
41
|
+
cv,
|
|
42
|
+
scoring = None
|
|
43
|
+
):
|
|
44
|
+
self.estimator = estimator
|
|
45
|
+
self.cv = cv
|
|
46
|
+
self.scoring = scoring
|
|
47
|
+
|
|
48
|
+
self._check()
|
|
49
|
+
self._setup()
|
|
50
|
+
|
|
51
|
+
def fit(
|
|
52
|
+
self,
|
|
53
|
+
X,
|
|
54
|
+
y
|
|
55
|
+
):
|
|
56
|
+
"""
|
|
57
|
+
Fit by repeated cross-fitting
|
|
58
|
+
|
|
59
|
+
Parameters
|
|
60
|
+
----------
|
|
61
|
+
|
|
62
|
+
X : array-like of shape (n_samples, n_features)
|
|
63
|
+
Training array, where `n_samples` is the sample size and
|
|
64
|
+
`n_features` is the number of features.
|
|
65
|
+
|
|
66
|
+
y : array-like of shape (n_samples,)
|
|
67
|
+
Target relative to X for classification or regression.
|
|
68
|
+
|
|
69
|
+
Returns
|
|
70
|
+
-------
|
|
71
|
+
self : object
|
|
72
|
+
Instance of fitted crosser.
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
cv = self.cv
|
|
76
|
+
estimators = []
|
|
77
|
+
features = self._features(X, y, on = "train")
|
|
78
|
+
targets = self._targets(X, y, on = "train")
|
|
79
|
+
for feature, target in zip(features, targets):
|
|
80
|
+
estimator = clone(self.estimator)
|
|
81
|
+
_ = estimator.fit(feature, target)
|
|
82
|
+
estimators.append(estimator)
|
|
83
|
+
self.estimators_ = estimators
|
|
84
|
+
|
|
85
|
+
if is_classifier(self):
|
|
86
|
+
label_binarizer = LabelBinarizer()
|
|
87
|
+
_ = label_binarizer.fit(y)
|
|
88
|
+
self.label_binarizer_ = label_binarizer
|
|
89
|
+
self.classes_ = sorted(set(y))
|
|
90
|
+
self._is_fitted = True
|
|
91
|
+
|
|
92
|
+
val_scores, train_scores, test_scores = self._scores(X, y)
|
|
93
|
+
self.val_scores_ = val_scores
|
|
94
|
+
self.train_scores_ = train_scores
|
|
95
|
+
self.test_scores_ = test_scores
|
|
96
|
+
|
|
97
|
+
return self
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def summarize(
|
|
101
|
+
self,
|
|
102
|
+
cross_fit = None,
|
|
103
|
+
combine = None,
|
|
104
|
+
reverse = False,
|
|
105
|
+
verbose = True
|
|
106
|
+
):
|
|
107
|
+
"""
|
|
108
|
+
Summarize repeated cross-fitting results
|
|
109
|
+
|
|
110
|
+
Parameters
|
|
111
|
+
----------
|
|
112
|
+
|
|
113
|
+
cross_fit : bool, default=None
|
|
114
|
+
If `True`, score values will be averaged across folds.
|
|
115
|
+
It is applicable if `n_folds` > 1. If applicable, `None`
|
|
116
|
+
means `True`; Otherwise, `None` means `False`.
|
|
117
|
+
|
|
118
|
+
combine : bool, default=None
|
|
119
|
+
If `True`, score values will be averaged across folds
|
|
120
|
+
and repeats. It is applicable if `n_splits` > 1. If
|
|
121
|
+
`n_repeats` > 1, `None` means `True`; Otherwise, `None`
|
|
122
|
+
means `False`.
|
|
123
|
+
|
|
124
|
+
reverse : bool, default=True
|
|
125
|
+
If `True`, negative score values will be reported.
|
|
126
|
+
Note that by default a larger score value means better
|
|
127
|
+
in `scikit-learn`.
|
|
128
|
+
|
|
129
|
+
verbose : bool, default=True
|
|
130
|
+
Controls the verbosity.
|
|
131
|
+
|
|
132
|
+
Returns
|
|
133
|
+
-------
|
|
134
|
+
summary : DataFrame
|
|
135
|
+
A summary for validation, train, and test scores (`val_score`,
|
|
136
|
+
`train_score`, and `test_score`). The validation scores
|
|
137
|
+
are only presented if `estimator.best_score_` is available.
|
|
138
|
+
|
|
139
|
+
"""
|
|
140
|
+
check_is_fitted(self)
|
|
141
|
+
estimator = self.estimator
|
|
142
|
+
cv = self.cv
|
|
143
|
+
scoring = self.scoring
|
|
144
|
+
n_splits = self._n_splits
|
|
145
|
+
n_repeats = self._n_repeats
|
|
146
|
+
n_folds = self._n_folds
|
|
147
|
+
|
|
148
|
+
val_scores = self.val_scores_
|
|
149
|
+
train_scores = self.train_scores_
|
|
150
|
+
test_scores = self.test_scores_
|
|
151
|
+
|
|
152
|
+
if combine is None:
|
|
153
|
+
if n_repeats > 1:
|
|
154
|
+
combine = True
|
|
155
|
+
else:
|
|
156
|
+
combine = False
|
|
157
|
+
|
|
158
|
+
if cross_fit is None:
|
|
159
|
+
if n_folds > 1:
|
|
160
|
+
cross_fit = True
|
|
161
|
+
else:
|
|
162
|
+
cross_fit = False
|
|
163
|
+
|
|
164
|
+
if reverse is True:
|
|
165
|
+
val_scores, train_scores, test_scores = -val_scores, -train_scores, -test_scores
|
|
166
|
+
|
|
167
|
+
if cross_fit:
|
|
168
|
+
val_scores = val_scores.reshape((n_repeats, n_folds)).mean(axis = 1)
|
|
169
|
+
train_scores = train_scores.reshape((n_repeats, n_folds)).mean(axis = 1)
|
|
170
|
+
test_scores = test_scores.reshape((n_repeats, n_folds)).mean(axis = 1)
|
|
171
|
+
|
|
172
|
+
if not combine:
|
|
173
|
+
if cross_fit:
|
|
174
|
+
index = pd.Index(
|
|
175
|
+
range(n_repeats),
|
|
176
|
+
name = "repeat")
|
|
177
|
+
else:
|
|
178
|
+
splits = list(range(self._n_splits))
|
|
179
|
+
repeats = [split // n_folds for split in splits]
|
|
180
|
+
folds = [split % n_folds for split in splits]
|
|
181
|
+
index = pd.MultiIndex.from_tuples(
|
|
182
|
+
list(zip(splits, repeats, folds)),
|
|
183
|
+
names = ["split", "repeat", "fold"])
|
|
184
|
+
summary = pd.DataFrame(
|
|
185
|
+
{"val_score": val_scores,
|
|
186
|
+
"train_score": train_scores,
|
|
187
|
+
"test_score": test_scores},
|
|
188
|
+
index = index
|
|
189
|
+
)
|
|
190
|
+
else:
|
|
191
|
+
index = pd.Index(
|
|
192
|
+
["mean", "std"],
|
|
193
|
+
name = "method")
|
|
194
|
+
summary = pd.DataFrame(
|
|
195
|
+
{"val_score": [np.mean(val_scores), np.std(val_scores)],
|
|
196
|
+
"train_score": [np.mean(train_scores), np.std(train_scores)],
|
|
197
|
+
"test_score": [np.mean(test_scores), np.std(test_scores)]},
|
|
198
|
+
index = index
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
if verbose:
|
|
202
|
+
print("Crosser Summary", end = " ")
|
|
203
|
+
print("(cross_fit=", cross_fit, ", " ,
|
|
204
|
+
"combine=", combine, ")", sep = "")
|
|
205
|
+
print(" + Estimator: ",
|
|
206
|
+
estimator.__class__.__name__, sep = "")
|
|
207
|
+
print(" + Cross-Validator: ",
|
|
208
|
+
cv.__class__.__name__,
|
|
209
|
+
" (", "n_folds=", n_folds,
|
|
210
|
+
", n_repeats=", n_repeats, ")", sep = "")
|
|
211
|
+
if callable(scoring):
|
|
212
|
+
print(" + Train/Test Scorer: ",
|
|
213
|
+
"Callable",
|
|
214
|
+
" (", "reverse=", reverse, ")", sep = "")
|
|
215
|
+
else:
|
|
216
|
+
print(" + Train/Test Scorer: ",
|
|
217
|
+
scoring.replace("_", " ").title(),
|
|
218
|
+
" (", "reverse=", reverse, ")", sep = "")
|
|
219
|
+
return summary
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def predict(
|
|
223
|
+
self,
|
|
224
|
+
X,
|
|
225
|
+
*,
|
|
226
|
+
split = None
|
|
227
|
+
):
|
|
228
|
+
check_is_fitted(self)
|
|
229
|
+
if split is None:
|
|
230
|
+
preds = np.array(
|
|
231
|
+
[estimator.predict(X)
|
|
232
|
+
for estimator in self.estimators_])
|
|
233
|
+
if is_classifier(self):
|
|
234
|
+
pred = np.apply_along_axis(
|
|
235
|
+
lambda x: np.argmax(np.bincount(x)),
|
|
236
|
+
axis = 0,
|
|
237
|
+
arr = preds)
|
|
238
|
+
else:
|
|
239
|
+
pred = preds.mean(axis = 0)
|
|
240
|
+
else:
|
|
241
|
+
pred = self.estimators_[split].predict(X)
|
|
242
|
+
return pred
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def predict_proba(
|
|
246
|
+
self,
|
|
247
|
+
X,
|
|
248
|
+
*,
|
|
249
|
+
split = None
|
|
250
|
+
):
|
|
251
|
+
check_is_fitted(self)
|
|
252
|
+
if split is None:
|
|
253
|
+
preds = np.array(
|
|
254
|
+
[estimator.predict_proba(X)
|
|
255
|
+
for estimator in self.estimators_])
|
|
256
|
+
pred = preds.mean(axis = 0)
|
|
257
|
+
else:
|
|
258
|
+
pred = self.estimators_[split].predict_proba(X)
|
|
259
|
+
return pred
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def predict_log_proba(
|
|
263
|
+
self,
|
|
264
|
+
X,
|
|
265
|
+
*,
|
|
266
|
+
split = None
|
|
267
|
+
):
|
|
268
|
+
check_is_fitted(self)
|
|
269
|
+
if split is None:
|
|
270
|
+
preds = np.array(
|
|
271
|
+
[estimator.predict_log_proba(X)
|
|
272
|
+
for estimator in self.estimators_])
|
|
273
|
+
pred = preds.mean(axis = 0)
|
|
274
|
+
else:
|
|
275
|
+
pred = self.estimators_[split].predict_log_proba(X)
|
|
276
|
+
return pred
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def decision_function(
|
|
280
|
+
self,
|
|
281
|
+
X,
|
|
282
|
+
*,
|
|
283
|
+
split = None
|
|
284
|
+
):
|
|
285
|
+
check_is_fitted(self)
|
|
286
|
+
if split is None:
|
|
287
|
+
preds = np.array(
|
|
288
|
+
[estimator.decision_function(X)
|
|
289
|
+
for estimator in self.estimators_])
|
|
290
|
+
pred = preds.mean(axis = 0)
|
|
291
|
+
else:
|
|
292
|
+
pred = self.estimators_[split].decision_function(X)
|
|
293
|
+
return pred
|
|
294
|
+
|
|
295
|
+
def _scores(
|
|
296
|
+
self,
|
|
297
|
+
X,
|
|
298
|
+
y
|
|
299
|
+
):
|
|
300
|
+
estimators = self.estimators_
|
|
301
|
+
scorer = self._scorer
|
|
302
|
+
n_repeats = self._n_repeats
|
|
303
|
+
n_folds = self._n_folds
|
|
304
|
+
|
|
305
|
+
features = zip(self._features(X, y, on = "train"),
|
|
306
|
+
self._features(X, y, on = "test"))
|
|
307
|
+
targets = zip(self._targets(X, y, on = "train"),
|
|
308
|
+
self._targets(X, y, on = "test"))
|
|
309
|
+
|
|
310
|
+
train_scores = []
|
|
311
|
+
val_scores = []
|
|
312
|
+
test_scores = []
|
|
313
|
+
for estimator, feature, target in zip(estimators, features, targets):
|
|
314
|
+
feature_train, feature_test = feature
|
|
315
|
+
target_train, target_test = target
|
|
316
|
+
train_score = scorer(estimator, feature_train, target_train)
|
|
317
|
+
test_score = scorer(estimator, feature_test, target_test)
|
|
318
|
+
if hasattr(estimator, "best_score_"):
|
|
319
|
+
val_score = estimator.best_score_
|
|
320
|
+
else:
|
|
321
|
+
val_score = np.nan
|
|
322
|
+
val_scores.append(val_score)
|
|
323
|
+
train_scores.append(train_score)
|
|
324
|
+
test_scores.append(test_score)
|
|
325
|
+
val_scores = np.array(val_scores)
|
|
326
|
+
train_scores = np.array(train_scores)
|
|
327
|
+
test_scores = np.array(test_scores)
|
|
328
|
+
return val_scores, train_scores, test_scores
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _features(
|
|
332
|
+
self,
|
|
333
|
+
X,
|
|
334
|
+
y,
|
|
335
|
+
on = "test"
|
|
336
|
+
):
|
|
337
|
+
cv = self.cv
|
|
338
|
+
features = []
|
|
339
|
+
for train_index, test_index in cv.split(X, y):
|
|
340
|
+
if on == "test":
|
|
341
|
+
index = test_index
|
|
342
|
+
else:
|
|
343
|
+
index = train_index
|
|
344
|
+
if isinstance(X, pd.DataFrame):
|
|
345
|
+
feature = X.iloc[index, :]
|
|
346
|
+
else:
|
|
347
|
+
feature = X[index, :]
|
|
348
|
+
features.append(feature)
|
|
349
|
+
return features
|
|
350
|
+
|
|
351
|
+
def _targets(
|
|
352
|
+
self,
|
|
353
|
+
X,
|
|
354
|
+
y,
|
|
355
|
+
binarize = None,
|
|
356
|
+
on = "test"
|
|
357
|
+
):
|
|
358
|
+
cv = self.cv
|
|
359
|
+
targets = []
|
|
360
|
+
for train_index, test_index in cv.split(X, y):
|
|
361
|
+
if on == "test":
|
|
362
|
+
index = test_index
|
|
363
|
+
else:
|
|
364
|
+
index = train_index
|
|
365
|
+
if isinstance(y, pd.Series):
|
|
366
|
+
target = y.iloc[index]
|
|
367
|
+
else:
|
|
368
|
+
target = y[index]
|
|
369
|
+
if is_classifier(self.estimator):
|
|
370
|
+
if binarize is True:
|
|
371
|
+
target = self.label_binarizer_.transform(target)
|
|
372
|
+
if target.shape[1] == 1:
|
|
373
|
+
target = np.append(1 - target, target, axis=1)
|
|
374
|
+
targets.append(target)
|
|
375
|
+
return targets
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _rvs(
|
|
379
|
+
self,
|
|
380
|
+
X,
|
|
381
|
+
y,
|
|
382
|
+
n_copies = None,
|
|
383
|
+
random_state = None
|
|
384
|
+
):
|
|
385
|
+
estimators = self.estimators_
|
|
386
|
+
features = self._features(X, y)
|
|
387
|
+
targets = self._targets(X, y)
|
|
388
|
+
rvs = []
|
|
389
|
+
for estimator, feature, target in zip(estimators, features, targets):
|
|
390
|
+
if hasattr(estimator, "sample"):
|
|
391
|
+
rv = estimator.sample(
|
|
392
|
+
feature,
|
|
393
|
+
target,
|
|
394
|
+
n_copies = n_copies,
|
|
395
|
+
random_state = random_state)
|
|
396
|
+
else:
|
|
397
|
+
rv = _sample(
|
|
398
|
+
estimator,
|
|
399
|
+
feature,
|
|
400
|
+
target,
|
|
401
|
+
n_copies = n_copies,
|
|
402
|
+
random_state = random_state)
|
|
403
|
+
rvs.append(rv)
|
|
404
|
+
return rvs
|
|
405
|
+
|
|
406
|
+
def _check(
|
|
407
|
+
self
|
|
408
|
+
):
|
|
409
|
+
cv = self.cv
|
|
410
|
+
scoring = self.scoring
|
|
411
|
+
|
|
412
|
+
allowed_cvs = {"KFold", "RepeatedKFold", "ShuffleSplit"}
|
|
413
|
+
if not isinstance(
|
|
414
|
+
cv,
|
|
415
|
+
tuple(getattr(model_selection, allowed_cv)
|
|
416
|
+
for allowed_cv in allowed_cvs)
|
|
417
|
+
):
|
|
418
|
+
raise ValueError(
|
|
419
|
+
"Support `cv` types are {}.".format(allowed_cvs))
|
|
420
|
+
else:
|
|
421
|
+
if isinstance(
|
|
422
|
+
cv, getattr(model_selection, "KFold")):
|
|
423
|
+
if cv.shuffle:
|
|
424
|
+
if cv.random_state is None:
|
|
425
|
+
raise ValueError(
|
|
426
|
+
"When `cv` is `KFold` and `cv.shuffle` is `True`, "
|
|
427
|
+
"`cv.random_state` cannot be `None`.")
|
|
428
|
+
else:
|
|
429
|
+
if cv.random_state is None:
|
|
430
|
+
raise ValueError(
|
|
431
|
+
"When `cv` is `RepeatedKFold` or `ShuffleSplit`, "
|
|
432
|
+
"`cv.random_state` cannot be `None`.")
|
|
433
|
+
|
|
434
|
+
if scoring is not None:
|
|
435
|
+
if not (isinstance(scoring, str) or callable(scoring)):
|
|
436
|
+
raise ValueError(
|
|
437
|
+
"Support `scoring` types are `str`, `callable`, or `None`")
|
|
438
|
+
if isinstance(scoring, str):
|
|
439
|
+
scorer_names = get_scorer_names()
|
|
440
|
+
if not scoring in get_scorer_names():
|
|
441
|
+
raise ValueError(
|
|
442
|
+
"Support `scoring` names are {}.".format(scorer_names))
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def _setup(
|
|
446
|
+
self
|
|
447
|
+
):
|
|
448
|
+
estimator = self.estimator
|
|
449
|
+
cv = self.cv
|
|
450
|
+
scoring = self.scoring
|
|
451
|
+
|
|
452
|
+
kf_cvs = {"KFold", "RepeatedKFold"}
|
|
453
|
+
ss_cvs = {"ShuffleSplit"}
|
|
454
|
+
n_splits = cv.get_n_splits()
|
|
455
|
+
if isinstance(
|
|
456
|
+
cv,
|
|
457
|
+
tuple(getattr(model_selection, kf_cv)
|
|
458
|
+
for kf_cv in kf_cvs)):
|
|
459
|
+
if hasattr(cv, "n_repeats"):
|
|
460
|
+
n_repeats = cv.n_repeats
|
|
461
|
+
else:
|
|
462
|
+
n_repeats = 1
|
|
463
|
+
else:
|
|
464
|
+
n_repeats = cv.get_n_splits()
|
|
465
|
+
n_folds = n_splits // n_repeats
|
|
466
|
+
|
|
467
|
+
if scoring is None:
|
|
468
|
+
if is_classifier(estimator):
|
|
469
|
+
scoring = "accuracy"
|
|
470
|
+
else:
|
|
471
|
+
scoring = "r2"
|
|
472
|
+
if isinstance(scoring, str):
|
|
473
|
+
scorer = get_scorer(scoring)
|
|
474
|
+
elif callable(scoring):
|
|
475
|
+
scorer = scoring
|
|
476
|
+
|
|
477
|
+
self.scoring = scoring
|
|
478
|
+
self._is_fitted = False
|
|
479
|
+
self._estimator_type = estimator._estimator_type
|
|
480
|
+
self._n_splits = n_splits
|
|
481
|
+
self._n_repeats = n_repeats
|
|
482
|
+
self._n_folds = n_folds
|
|
483
|
+
self._scorer = scorer
|
|
484
|
+
|
|
485
|
+
def __sklearn_is_fitted__(self):
|
|
486
|
+
return hasattr(self, "_is_fitted") and self._is_fitted
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
|