forked from hyperactive-project/Hyperactive
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsklearn_cv.py
More file actions
322 lines (274 loc) · 11 KB
/
Copy pathsklearn_cv.py
File metadata and controls
322 lines (274 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
"""Experiment adapter for sklearn cross-validation experiments."""
# copyright: hyperactive developers, MIT License (see LICENSE file)
from sklearn import clone
from sklearn.metrics import check_scoring
from sklearn.model_selection import cross_validate
from sklearn.utils.validation import _num_samples
from hyperactive.base import BaseExperiment
class SklearnCvExperiment(BaseExperiment):
"""Experiment adapter for sklearn cross-validation experiments.
This class is used to perform cross-validation experiments using a given
sklearn estimator. It allows for hyperparameter tuning and evaluation of
the model's performance using cross-validation.
The score returned is the mean of the cross-validation scores,
of applying cross-validation to ``estimator`` with the parameters given in
``score`` ``params``.
The cross-validation performed is specified by the ``cv`` parameter,
and the scoring metric is specified by the ``scoring`` parameter.
The ``X`` and ``y`` parameters are the input data and target values,
which are used in fit/predict cross-validation.
Parameters
----------
estimator : sklearn estimator
The estimator to be used for the experiment.
X : array-like, shape (n_samples, n_features)
The input data for the model.
y : array-like, shape (n_samples,) or (n_samples, n_outputs)
The target values for the model.
cv : int or cross-validation generator, default = KFold(n_splits=3, shuffle=True)
The number of folds or cross-validation strategy to be used.
If int, the cross-validation used is KFold(n_splits=cv, shuffle=True).
scoring : callable or str, default = accuracy_score or mean_squared_error
sklearn scoring function or metric to evaluate the model's performance.
Default is determined by the type of estimator:
``accuracy_score`` for classifiers, and
``mean_squared_error`` for regressors, as per sklearn convention
through the default ``score`` method of the estimator.
Example
-------
>>> from hyperactive.experiment.integrations import SklearnCvExperiment
>>> from sklearn.datasets import load_iris
>>> from sklearn.svm import SVC
>>> from sklearn.metrics import accuracy_score
>>> from sklearn.model_selection import KFold
>>>
>>> X, y = load_iris(return_X_y=True)
>>>
>>> sklearn_exp = SklearnCvExperiment(
... estimator=SVC(),
... scoring=accuracy_score,
... cv=KFold(n_splits=3, shuffle=True),
... X=X,
... y=y,
... )
>>> params = {"C": 1.0, "kernel": "linear"}
>>> score, add_info = sklearn_exp.score(params)
For default choices of ``scoring`` and ``cv``:
>>> sklearn_exp = SklearnCvExperiment(
... estimator=SVC(),
... X=X,
... y=y,
... )
>>> params = {"C": 1.0, "kernel": "linear"}
>>> score, add_info = sklearn_exp.score(params)
Quick call without metadata return or dictionary:
>>> score = sklearn_exp(C=1.0, kernel="linear")
"""
def __init__(self, estimator, X, y, scoring=None, cv=None):
self.estimator = estimator
self.X = X
self.y = y
self.scoring = scoring
self.cv = cv
super().__init__()
if cv is None:
from sklearn.model_selection import KFold
self._cv = KFold(n_splits=3, shuffle=True)
elif isinstance(cv, int):
from sklearn.model_selection import KFold
self._cv = KFold(n_splits=cv, shuffle=True)
else:
self._cv = cv
# check if scoring is a scorer by checking for "estimator" in signature
if scoring is None:
self._scoring = check_scoring(self.estimator)
# check using inspect.signature for "estimator" in signature
elif callable(scoring):
from inspect import signature
if "estimator" in signature(scoring).parameters:
self._scoring = scoring
else:
from sklearn.metrics import make_scorer
self._scoring = make_scorer(scoring)
self.scorer_ = self._scoring
# Set the sign of the scoring function
if hasattr(self._scoring, "_score"):
score_func = self._scoring._score_func
_sign = _guess_sign_of_sklmetric(score_func)
_sign_str = "higher" if _sign == 1 else "lower"
self.set_tags(**{"property:higher_or_lower_is_better": _sign_str})
def _paramnames(self):
"""Return the parameter names of the search.
Returns
-------
list of str
The parameter names of the search parameters.
"""
return list(self.estimator.get_params().keys())
def _evaluate(self, params):
"""Evaluate the parameters.
Parameters
----------
params : dict with string keys
Parameters to evaluate.
Returns
-------
float
The value of the parameters as per evaluation.
dict
Additional metadata about the search.
"""
estimator = clone(self.estimator)
estimator.set_params(**params)
cv_results = cross_validate(
estimator,
self.X,
self.y,
scoring=self._scoring,
cv=self._cv,
)
add_info_d = {
"score_time": cv_results["score_time"],
"fit_time": cv_results["fit_time"],
"n_test_samples": _num_samples(self.X),
}
return cv_results["test_score"].mean(), add_info_d
@classmethod
def get_test_params(cls, parameter_set="default"):
"""Return testing parameter settings for the skbase object.
``get_test_params`` is a unified interface point to store
parameter settings for testing purposes. This function is also
used in ``create_test_instance`` and ``create_test_instances_and_names``
to construct test instances.
``get_test_params`` should return a single ``dict``, or a ``list`` of ``dict``.
Each ``dict`` is a parameter configuration for testing,
and can be used to construct an "interesting" test instance.
A call to ``cls(**params)`` should
be valid for all dictionaries ``params`` in the return of ``get_test_params``.
The ``get_test_params`` need not return fixed lists of dictionaries,
it can also return dynamic or stochastic parameter settings.
Parameters
----------
parameter_set : str, default="default"
Name of the set of test parameters to return, for use in tests. If no
special parameters are defined for a value, will return `"default"` set.
Returns
-------
params : dict or list of dict, default = {}
Parameters to create testing instances of the class
Each dict are parameters to construct an "interesting" test instance, i.e.,
`MyClass(**params)` or `MyClass(**params[i])` creates a valid test instance.
`create_test_instance` uses the first (or only) dictionary in `params`
"""
from sklearn.datasets import load_diabetes, load_iris
from sklearn.svm import SVC, SVR
from sklearn.metrics import accuracy_score, mean_absolute_error
from sklearn.model_selection import KFold
X, y = load_iris(return_X_y=True)
params_classif = {
"estimator": SVC(),
"scoring": accuracy_score,
"cv": KFold(n_splits=3, shuffle=True),
"X": X,
"y": y,
}
X, y = load_diabetes(return_X_y=True)
params_regress = {
"estimator": SVR(),
"scoring": mean_absolute_error,
"cv": 2,
"X": X,
"y": y,
}
X, y = load_diabetes(return_X_y=True)
params_all_default = {
"estimator": SVR(),
"X": X,
"y": y,
}
return [params_classif, params_regress, params_all_default]
@classmethod
def _get_score_params(self):
"""Return settings for testing score/evaluate functions. Used in tests only.
Returns a list, the i-th element should be valid arguments for
self.evaluate and self.score, of an instance constructed with
self.get_test_params()[i].
Returns
-------
list of dict
The parameters to be used for scoring.
"""
score_params_classif = {"C": 1.0, "kernel": "linear"}
score_params_regress = {"C": 1.0, "kernel": "linear"}
score_params_defaults = {"C": 1.0, "kernel": "linear"}
return [score_params_classif, score_params_regress, score_params_defaults]
def _guess_sign_of_sklmetric(scorer):
"""Guess the sign of a sklearn metric scorer.
Parameters
----------
scorer : callable
The sklearn metric scorer to guess the sign for.
Returns
-------
int
1 if higher scores are better, -1 if lower scores are better.
"""
HIGHER_IS_BETTER = {
# Classification
"accuracy_score": True,
"auc": True,
"average_precision_score": True,
"balanced_accuracy_score": True,
"brier_score_loss": False,
"class_likelihood_ratios": False,
"cohen_kappa_score": True,
"d2_log_loss_score": True,
"dcg_score": True,
"f1_score": True,
"fbeta_score": True,
"hamming_loss": False,
"hinge_loss": False,
"jaccard_score": True,
"log_loss": False,
"matthews_corrcoef": True,
"ndcg_score": True,
"precision_score": True,
"recall_score": True,
"roc_auc_score": True,
"top_k_accuracy_score": True,
"zero_one_loss": False,
# Regression
"d2_absolute_error_score": True,
"d2_pinball_score": True,
"d2_tweedie_score": True,
"explained_variance_score": True,
"max_error": False,
"mean_absolute_error": False,
"mean_absolute_percentage_error": False,
"mean_gamma_deviance": False,
"mean_pinball_loss": False,
"mean_poisson_deviance": False,
"mean_squared_error": False,
"mean_squared_log_error": False,
"mean_tweedie_deviance": False,
"median_absolute_error": False,
"r2_score": True,
"root_mean_squared_error": False,
"root_mean_squared_log_error": False,
}
scorer_name = getattr(scorer, "__name__", None)
if hasattr(scorer, "greater_is_better"):
return 1 if scorer.greater_is_better else -1
elif scorer_name in HIGHER_IS_BETTER:
return 1 if HIGHER_IS_BETTER[scorer_name] else -1
elif scorer_name.endswith("_score"):
# If the scorer name ends with "_score", we assume higher is better
return 1
elif scorer_name.endswith("_loss") or scorer_name.endswith("_deviance"):
# If the scorer name ends with "_loss", we assume lower is better
return -1
elif scorer_name.endswith("_error"):
return -1
else:
# If we cannot determine the sign, we assume lower is better
return -1