-
Notifications
You must be signed in to change notification settings - Fork 90
/
_template.py
308 lines (247 loc) · 10.3 KB
/
_template.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
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
"""
This is a module to be used as a reference for building other modules
"""
# Authors: scikit-learn-contrib developers
# License: BSD 3 clause
import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin, TransformerMixin, _fit_context
from sklearn.metrics import euclidean_distances
from sklearn.utils.multiclass import check_classification_targets
from sklearn.utils.validation import check_is_fitted
class TemplateEstimator(BaseEstimator):
"""A template estimator to be used as a reference implementation.
For more information regarding how to build your own estimator, read more
in the :ref:`User Guide <user_guide>`.
Parameters
----------
demo_param : str, default='demo_param'
A parameter used for demonstration of how to pass and store parameters.
Attributes
----------
is_fitted_ : bool
A boolean indicating whether the estimator has been fitted.
n_features_in_ : int
Number of features seen during :term:`fit`.
feature_names_in_ : ndarray of shape (`n_features_in_`,)
Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.
Examples
--------
>>> from skltemplate import TemplateEstimator
>>> import numpy as np
>>> X = np.arange(100).reshape(100, 1)
>>> y = np.zeros((100, ))
>>> estimator = TemplateEstimator()
>>> estimator.fit(X, y)
TemplateEstimator()
"""
# This is a dictionary allowing to define the type of parameters.
# It used to validate parameter within the `_fit_context` decorator.
_parameter_constraints = {
"demo_param": [str],
}
def __init__(self, demo_param="demo_param"):
self.demo_param = demo_param
@_fit_context(prefer_skip_nested_validation=True)
def fit(self, X, y):
"""A reference implementation of a fitting function.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
The training input samples.
y : array-like, shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels in classification, real numbers in
regression).
Returns
-------
self : object
Returns self.
"""
# `_validate_data` is defined in the `BaseEstimator` class.
# It allows to:
# - run different checks on the input data;
# - define some attributes associated to the input data: `n_features_in_` and
# `feature_names_in_`.
X, y = self._validate_data(X, y, accept_sparse=True)
self.is_fitted_ = True
# `fit` should always return `self`
return self
def predict(self, X):
"""A reference implementation of a predicting function.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
The training input samples.
Returns
-------
y : ndarray, shape (n_samples,)
Returns an array of ones.
"""
# Check if fit had been called
check_is_fitted(self)
# We need to set reset=False because we don't want to overwrite `n_features_in_`
# `feature_names_in_` but only check that the shape is consistent.
X = self._validate_data(X, accept_sparse=True, reset=False)
return np.ones(X.shape[0], dtype=np.int64)
# Note that the mixin class should always be on the left of `BaseEstimator` to ensure
# the MRO works as expected.
class TemplateClassifier(ClassifierMixin, BaseEstimator):
"""An example classifier which implements a 1-NN algorithm.
For more information regarding how to build your own classifier, read more
in the :ref:`User Guide <user_guide>`.
Parameters
----------
demo_param : str, default='demo'
A parameter used for demonstation of how to pass and store paramters.
Attributes
----------
X_ : ndarray, shape (n_samples, n_features)
The input passed during :meth:`fit`.
y_ : ndarray, shape (n_samples,)
The labels passed during :meth:`fit`.
classes_ : ndarray, shape (n_classes,)
The classes seen at :meth:`fit`.
n_features_in_ : int
Number of features seen during :term:`fit`.
feature_names_in_ : ndarray of shape (`n_features_in_`,)
Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.
Examples
--------
>>> from sklearn.datasets import load_iris
>>> from skltemplate import TemplateClassifier
>>> X, y = load_iris(return_X_y=True)
>>> clf = TemplateClassifier().fit(X, y)
>>> clf.predict(X)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
"""
# This is a dictionary allowing to define the type of parameters.
# It used to validate parameter within the `_fit_context` decorator.
_parameter_constraints = {
"demo_param": [str],
}
def __init__(self, demo_param="demo"):
self.demo_param = demo_param
@_fit_context(prefer_skip_nested_validation=True)
def fit(self, X, y):
"""A reference implementation of a fitting function for a classifier.
Parameters
----------
X : array-like, shape (n_samples, n_features)
The training input samples.
y : array-like, shape (n_samples,)
The target values. An array of int.
Returns
-------
self : object
Returns self.
"""
# `_validate_data` is defined in the `BaseEstimator` class.
# It allows to:
# - run different checks on the input data;
# - define some attributes associated to the input data: `n_features_in_` and
# `feature_names_in_`.
X, y = self._validate_data(X, y)
# We need to make sure that we have a classification task
check_classification_targets(y)
# classifier should always store the classes seen during `fit`
self.classes_ = np.unique(y)
# Store the training data to predict later
self.X_ = X
self.y_ = y
# Return the classifier
return self
def predict(self, X):
"""A reference implementation of a prediction for a classifier.
Parameters
----------
X : array-like, shape (n_samples, n_features)
The input samples.
Returns
-------
y : ndarray, shape (n_samples,)
The label for each sample is the label of the closest sample
seen during fit.
"""
# Check if fit had been called
check_is_fitted(self)
# Input validation
# We need to set reset=False because we don't want to overwrite `n_features_in_`
# `feature_names_in_` but only check that the shape is consistent.
X = self._validate_data(X, reset=False)
closest = np.argmin(euclidean_distances(X, self.X_), axis=1)
return self.y_[closest]
# Note that the mixin class should always be on the left of `BaseEstimator` to ensure
# the MRO works as expected.
class TemplateTransformer(TransformerMixin, BaseEstimator):
"""An example transformer that returns the element-wise square root.
For more information regarding how to build your own transformer, read more
in the :ref:`User Guide <user_guide>`.
Parameters
----------
demo_param : str, default='demo'
A parameter used for demonstation of how to pass and store paramters.
Attributes
----------
n_features_in_ : int
Number of features seen during :term:`fit`.
feature_names_in_ : ndarray of shape (`n_features_in_`,)
Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.
"""
# This is a dictionary allowing to define the type of parameters.
# It used to validate parameter within the `_fit_context` decorator.
_parameter_constraints = {
"demo_param": [str],
}
def __init__(self, demo_param="demo"):
self.demo_param = demo_param
@_fit_context(prefer_skip_nested_validation=True)
def fit(self, X, y=None):
"""A reference implementation of a fitting function for a transformer.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
The training input samples.
y : None
There is no need of a target in a transformer, yet the pipeline API
requires this parameter.
Returns
-------
self : object
Returns self.
"""
X = self._validate_data(X, accept_sparse=True)
# Return the transformer
return self
def transform(self, X):
"""A reference implementation of a transform function.
Parameters
----------
X : {array-like, sparse-matrix}, shape (n_samples, n_features)
The input samples.
Returns
-------
X_transformed : array, shape (n_samples, n_features)
The array containing the element-wise square roots of the values
in ``X``.
"""
# Since this is a stateless transformer, we should not call `check_is_fitted`.
# Common test will check for this particularly.
# Input validation
# We need to set reset=False because we don't want to overwrite `n_features_in_`
# `feature_names_in_` but only check that the shape is consistent.
X = self._validate_data(X, accept_sparse=True, reset=False)
return np.sqrt(X)
def _more_tags(self):
# This is a quick example to show the tags API:\
# https://scikit-learn.org/dev/developers/develop.html#estimator-tags
# Here, our transformer does not do any operation in `fit` and only validate
# the parameters. Thus, it is stateless.
return {"stateless": True}