1
|
|
|
from sklearn.model_selection import cross_val_score |
2
|
|
|
from sklearn.ensemble import GradientBoostingRegressor |
3
|
|
|
|
4
|
|
|
|
5
|
|
|
from hyperactive import BaseExperiment |
6
|
|
|
|
7
|
|
|
|
8
|
|
|
class SklearnExperiment(BaseExperiment): |
9
|
|
|
""" |
10
|
|
|
Initializes the SklearnExperiment with the given estimator, data, and cross-validation settings. |
11
|
|
|
|
12
|
|
|
Parameters |
13
|
|
|
---------- |
14
|
|
|
estimator : object |
15
|
|
|
The machine learning estimator to be used for the experiment. |
16
|
|
|
X : array-like |
17
|
|
|
The input data for training the model. |
18
|
|
|
y : array-like |
19
|
|
|
The target values corresponding to the input data. |
20
|
|
|
cv : int, optional |
21
|
|
|
The number of cross-validation folds (default is 4). |
22
|
|
|
""" |
23
|
|
|
|
24
|
|
|
def __init__(self, estimator, X, y, cv=4): |
25
|
|
|
super().__init__() |
26
|
|
|
|
27
|
|
|
self.estimator = estimator |
28
|
|
|
self.X = X |
29
|
|
|
self.y = y |
30
|
|
|
self.cv = cv |
31
|
|
|
|
32
|
|
|
def _score(self, **params): |
33
|
|
|
model = self.estimator(**params) |
34
|
|
|
scores = cross_val_score(model, self.X, self.y, cv=self.cv) |
35
|
|
|
return scores.mean() |
36
|
|
|
|
37
|
|
|
|
38
|
|
|
class GradientBoostingExperiment(BaseExperiment): |
39
|
|
|
""" |
40
|
|
|
A class for conducting experiments with Gradient Boosting Regressor using cross-validation. |
41
|
|
|
|
42
|
|
|
This class inherits from BaseExperiment and allows users to perform experiments |
43
|
|
|
with the GradientBoostingRegressor from sklearn. Users can specify the input |
44
|
|
|
features, target values, and the number of cross-validation folds. |
45
|
|
|
|
46
|
|
|
Attributes: |
47
|
|
|
estimator (type): The regression model to be used, default is GradientBoostingRegressor. |
48
|
|
|
X (array-like): The input features for the model. |
49
|
|
|
y (array-like): The target values for the model. |
50
|
|
|
cv (int): The number of cross-validation folds. |
51
|
|
|
|
52
|
|
|
Methods: |
53
|
|
|
_score(**params): Evaluates the model using cross-validation and returns the mean score. |
54
|
|
|
""" |
55
|
|
|
|
56
|
|
|
def __init__(self, X, y, cv=4): |
57
|
|
|
super().__init__() |
58
|
|
|
|
59
|
|
|
self.estimator = GradientBoostingRegressor # The user could also predefine the estimator |
60
|
|
|
self.X = X |
61
|
|
|
self.y = y |
62
|
|
|
self.cv = cv |
63
|
|
|
|
64
|
|
|
def _score(self, **params): |
65
|
|
|
model = self.estimator(**params) |
66
|
|
|
scores = cross_val_score(model, self.X, self.y, cv=self.cv) |
67
|
|
|
return scores.mean() |
68
|
|
|
|