-
Notifications
You must be signed in to change notification settings - Fork 210
/
stacking.py
282 lines (224 loc) · 9.61 KB
/
stacking.py
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
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import numpy
from sklearn.base import MetaEstimatorMixin, clone
from sklearn.utils.metaestimators import _BaseComposition, available_if
from ..base import SurvivalAnalysisMixin
def _meta_estimator_has(attr):
"""Check that meta_estimator has `attr`.
Used together with `available_if`."""
def check(self):
# raise original `AttributeError` if `attr` does not exist
getattr(self.meta_estimator, attr)
return True
return check
class Stacking(MetaEstimatorMixin, SurvivalAnalysisMixin, _BaseComposition):
"""Meta estimator that combines multiple base learners.
By default, base estimators' output corresponds to the array returned
by `predict_proba`. If `predict_proba` is not available or `probabilities = False`,
the output of `predict` is used.
Parameters
----------
meta_estimator : instance of estimator
The estimator that is used to combine the output of different
base estimators.
base_estimators : list
List of (name, estimator) tuples (implementing fit/predict) that are
part of the ensemble.
probabilities : bool, optional, default: True
Whether to allow using `predict_proba` method of base learners, if available.
Attributes
----------
estimators_ : list of estimators
The elements of the estimators parameter, having been fitted on the
training data.
named_estimators_ : dict
Attribute to access any fitted sub-estimators by name.
final_estimator_ : estimator
The estimator which combines the output of `estimators_`.
n_features_in_ : int
Number of features seen during ``fit``.
feature_names_in_ : ndarray of shape (`n_features_in_`,)
Names of features seen during ``fit``. Defined only when `X`
has feature names that are all strings.
"""
def __init__(self, meta_estimator, base_estimators, probabilities=True):
self.meta_estimator = meta_estimator
self.base_estimators = base_estimators
self.probabilities = probabilities
self._extra_params = ["meta_estimator", "base_estimators", "probabilities"]
def _validate_estimators(self):
names, estimators = zip(*self.base_estimators)
if len(set(names)) != len(self.base_estimators):
raise ValueError("Names provided are not unique: %s" % (names,))
for t in estimators:
if not hasattr(t, "fit") or not (hasattr(t, "predict") or hasattr(t, "predict_proba")):
raise TypeError("All base estimators should implement "
"fit and predict/predict_proba"
" '%s' (type %s) doesn't)" % (t, type(t)))
if not hasattr(self.meta_estimator, "fit"):
raise TypeError("meta estimator should implement fit "
"'%s' (type %s) doesn't)"
% (self.meta_estimator, type(self.meta_estimator)))
def set_params(self, **params):
"""
Set the parameters of an estimator from the ensemble.
Valid parameter keys can be listed with `get_params()`. Note that you
can directly set the parameters of the estimators contained in
`estimators`.
Parameters
----------
**params : keyword arguments
Specific parameters using e.g.
`set_params(parameter_name=new_value)`. In addition, to setting the
parameters of the estimator, the individual estimator of the
estimators can also be set, or can be removed by setting them to
'drop'.
Returns
-------
self : object
Estimator instance.
"""
super()._set_params("base_estimators", **params)
return self
def get_params(self, deep=True):
"""
Get the parameters of an estimator from the ensemble.
Returns the parameters given in the constructor as well as the
estimators contained within the `estimators` parameter.
Parameters
----------
deep : bool, default=True
Setting it to True gets the various estimators and the parameters
of the estimators as well.
Returns
-------
params : dict
Parameter and estimator names mapped to their values or parameter
names mapped to their values.
"""
return super()._get_params("base_estimators", deep=deep)
def _split_fit_params(self, fit_params):
fit_params_steps = {step: {} for step, _ in self.base_estimators}
for pname, pval in fit_params.items():
step, param = pname.split('__', 1)
fit_params_steps[step][param] = pval
return fit_params_steps
def _fit_estimators(self, X, y=None, **fit_params):
if hasattr(self, "feature_names_in_"):
# Delete the attribute when the estimator is fitted on a new dataset
# that has no feature names.
delattr(self, "feature_names_in_")
fit_params_steps = self._split_fit_params(fit_params)
names = []
estimators = []
for name, estimator in self.base_estimators:
est = clone(estimator).fit(X, y, **fit_params_steps[name])
if hasattr(est, "n_features_in_"):
self.n_features_in_ = est.n_features_in_
if hasattr(est, "feature_names_in_"):
self.feature_names_in_ = est.feature_names_in_
estimators.append(est)
names.append(name)
self.named_estimators = dict(zip(names, estimators))
self.estimators_ = estimators
def _predict_estimators(self, X):
Xt = None
start = 0
for estimator in self.estimators_:
if self.probabilities and hasattr(estimator, "predict_proba"):
p = estimator.predict_proba(X)
else:
p = estimator.predict(X)
if p.ndim == 1:
p = p[:, numpy.newaxis]
if Xt is None:
# assume that prediction array has the same size for all base learners
n_classes = p.shape[1]
Xt = numpy.empty((p.shape[0], n_classes * len(self.base_estimators)), order='F')
Xt[:, slice(start, start + n_classes)] = p
start += n_classes
return Xt
def __len__(self):
return len(self.base_estimators)
def fit(self, X, y=None, **fit_params):
"""Fit base estimators.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Training data.
y : array-like, optional
Target data if base estimators are supervised.
Returns
-------
self
"""
self._validate_estimators()
self._fit_estimators(X, y, **fit_params)
Xt = self._predict_estimators(X)
self.final_estimator_ = self.meta_estimator.fit(Xt, y)
return self
@available_if(_meta_estimator_has('predict'))
def predict(self, X):
"""Perform prediction.
Only available of the meta estimator has a predict method.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data with samples to predict.
Returns
-------
prediction : array, shape = (n_samples, n_dim)
Prediction of meta estimator that combines
predictions of base estimators. `n_dim` depends
on the return value of meta estimator's `predict`
method.
"""
Xt = self._predict_estimators(X)
return self.final_estimator_.predict(Xt)
@available_if(_meta_estimator_has('predict_proba'))
def predict_proba(self, X):
"""Perform prediction.
Only available of the meta estimator has a predict_proba method.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data with samples to predict.
Returns
-------
prediction : ndarray, shape = (n_samples, n_dim)
Prediction of meta estimator that combines
predictions of base estimators. `n_dim` depends
on the return value of meta estimator's `predict`
method.
"""
Xt = self._predict_estimators(X)
return self.final_estimator_.predict_proba(Xt)
@available_if(_meta_estimator_has('predict_log_proba'))
def predict_log_proba(self, X):
"""Perform prediction.
Only available of the meta estimator has a predict_log_proba method.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data with samples to predict.
Returns
-------
prediction : ndarray, shape = (n_samples, n_dim)
Prediction of meta estimator that combines
predictions of base estimators. `n_dim` depends
on the return value of meta estimator's `predict`
method.
"""
Xt = self._predict_estimators(X)
return self.final_estimator_.predict_log_proba(Xt)