/
classifier.py
357 lines (290 loc) · 11.6 KB
/
classifier.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
"""NeuralNet subclasses for classification tasks."""
import re
import numpy as np
from sklearn.base import ClassifierMixin
import torch
from torch.utils.data import DataLoader
from skorch import NeuralNet
from skorch.callbacks import EpochTimer
from skorch.callbacks import PrintLog
from skorch.callbacks import EpochScoring
from skorch.callbacks import PassthroughScoring
from skorch.dataset import ValidSplit
from skorch.utils import get_dim, to_numpy
from skorch.utils import is_dataset
neural_net_clf_doc_start = """NeuralNet for classification tasks
Use this specifically if you have a standard classification task,
with input data X and target y.
"""
neural_net_clf_additional_text = """
criterion : torch criterion (class, default=torch.nn.NLLLoss)
Negative log likelihood loss. Note that the module should return
probabilities, the log is applied during ``get_loss``.
classes : None or list (default=None)
If None, the ``classes_`` attribute will be inferred from the
``y`` data passed to ``fit``. If a non-empty list is passed,
that list will be returned as ``classes_``. If the initial
skorch behavior should be restored, i.e. raising an
``AttributeError``, pass an empty list."""
neural_net_clf_additional_attribute = """classes_ : array, shape (n_classes, )
A list of class labels known to the classifier.
"""
def get_neural_net_clf_doc(doc):
doc = neural_net_clf_doc_start + " " + doc.split("\n ", 4)[-1]
pattern = re.compile(r'(\n\s+)(criterion .*\n)(\s.+){1,99}')
start, end = pattern.search(doc).span()
doc = doc[:start] + neural_net_clf_additional_text + doc[end:]
doc = doc + neural_net_clf_additional_attribute
return doc
# pylint: disable=missing-docstring
class NeuralNetClassifier(NeuralNet, ClassifierMixin):
__doc__ = get_neural_net_clf_doc(NeuralNet.__doc__)
def __init__(
self,
module,
*args,
criterion=torch.nn.NLLLoss,
train_split=ValidSplit(5, stratified=True),
classes=None,
**kwargs
):
super(NeuralNetClassifier, self).__init__(
module,
*args,
criterion=criterion,
train_split=train_split,
**kwargs
)
self.classes = classes
@property
def _default_callbacks(self):
return [
('epoch_timer', EpochTimer()),
('train_loss', PassthroughScoring(
name='train_loss',
on_train=True,
)),
('valid_loss', PassthroughScoring(
name='valid_loss',
)),
('valid_acc', EpochScoring(
'accuracy',
name='valid_acc',
lower_is_better=False,
)),
('print_log', PrintLog()),
]
@property
def classes_(self):
if self.classes is not None:
if not len(self.classes):
raise AttributeError("{} has no attribute 'classes_'".format(
self.__class__.__name__))
return self.classes
return self.classes_inferred_
# pylint: disable=signature-differs
def check_data(self, X, y):
if (
(y is None) and
(not is_dataset(X)) and
(self.iterator_train is DataLoader)
):
msg = ("No y-values are given (y=None). You must either supply a "
"Dataset as X or implement your own DataLoader for "
"training (and your validation) and supply it using the "
"``iterator_train`` and ``iterator_valid`` parameters "
"respectively.")
raise ValueError(msg)
if y is not None:
# pylint: disable=attribute-defined-outside-init
self.classes_inferred_ = np.unique(to_numpy(y))
# pylint: disable=arguments-differ
def get_loss(self, y_pred, y_true, *args, **kwargs):
if isinstance(self.criterion_, torch.nn.NLLLoss):
eps = torch.finfo(y_pred.dtype).eps
y_pred = torch.log(y_pred + eps)
return super().get_loss(y_pred, y_true, *args, **kwargs)
# pylint: disable=signature-differs
def fit(self, X, y, **fit_params):
"""See ``NeuralNet.fit``.
In contrast to ``NeuralNet.fit``, ``y`` is non-optional to
avoid mistakenly forgetting about ``y``. However, ``y`` can be
set to ``None`` in case it is derived dynamically from
``X``.
"""
# pylint: disable=useless-super-delegation
# this is actually a pylint bug:
# https://github.com/PyCQA/pylint/issues/1085
return super(NeuralNetClassifier, self).fit(X, y, **fit_params)
def predict_proba(self, X):
"""Where applicable, return probability estimates for
samples.
If the module's forward method returns multiple outputs as a
tuple, it is assumed that the first output contains the
relevant information and the other values are ignored. If all
values are relevant, consider using
:func:`~skorch.NeuralNet.forward` instead.
Parameters
----------
X : input data, compatible with skorch.dataset.Dataset
By default, you should be able to pass:
* numpy arrays
* torch tensors
* pandas DataFrame or Series
* scipy sparse CSR matrices
* a dictionary of the former three
* a list/tuple of the former three
* a Dataset
If this doesn't work with your data, you have to pass a
``Dataset`` that can deal with the data.
Returns
-------
y_proba : numpy ndarray
"""
# Only the docstring changed from parent.
# pylint: disable=useless-super-delegation
return super().predict_proba(X)
def predict(self, X):
"""Where applicable, return class labels for samples in X.
If the module's forward method returns multiple outputs as a
tuple, it is assumed that the first output contains the
relevant information and the other values are ignored. If all
values are relevant, consider using
:func:`~skorch.NeuralNet.forward` instead.
Parameters
----------
X : input data, compatible with skorch.dataset.Dataset
By default, you should be able to pass:
* numpy arrays
* torch tensors
* pandas DataFrame or Series
* scipy sparse CSR matrices
* a dictionary of the former three
* a list/tuple of the former three
* a Dataset
If this doesn't work with your data, you have to pass a
``Dataset`` that can deal with the data.
Returns
-------
y_pred : numpy ndarray
"""
return self.predict_proba(X).argmax(axis=1)
neural_net_binary_clf_doc_start = """NeuralNet for binary classification tasks
Use this specifically if you have a binary classification task,
with input data X and target y. y must be 1d.
"""
neural_net_binary_clf_criterion_text = """
criterion : torch criterion (class, default=torch.nn.BCEWithLogitsLoss)
Binary cross entropy loss with logits. Note that the module should return
the logit of probabilities with shape (batch_size, ).
threshold : float (default=0.5)
Probabilities above this threshold is classified as 1. ``threshold``
is used by ``predict`` and ``predict_proba`` for classification."""
def get_neural_net_binary_clf_doc(doc):
doc = neural_net_binary_clf_doc_start + " " + doc.split("\n ", 4)[-1]
pattern = re.compile(r'(\n\s+)(criterion .*\n)(\s.+){1,99}')
start, end = pattern.search(doc).span()
doc = doc[:start] + neural_net_binary_clf_criterion_text + doc[end:]
return doc
class NeuralNetBinaryClassifier(NeuralNet, ClassifierMixin):
# pylint: disable=missing-docstring
__doc__ = get_neural_net_binary_clf_doc(NeuralNet.__doc__)
def __init__(
self,
module,
*args,
criterion=torch.nn.BCEWithLogitsLoss,
train_split=ValidSplit(5, stratified=True),
threshold=0.5,
**kwargs
):
super().__init__(
module,
criterion=criterion,
train_split=train_split,
*args,
**kwargs
)
self.threshold = threshold
@property
def _default_callbacks(self):
return [
('epoch_timer', EpochTimer()),
('train_loss', PassthroughScoring(
name='train_loss',
on_train=True,
)),
('valid_loss', PassthroughScoring(
name='valid_loss',
)),
('valid_acc', EpochScoring(
'accuracy',
name='valid_acc',
lower_is_better=False,
)),
('print_log', PrintLog()),
]
@property
def classes_(self):
return [0, 1]
# pylint: disable=signature-differs
def check_data(self, X, y):
super().check_data(X, y)
if (not is_dataset(X)) and (get_dim(y) != 1):
raise ValueError("The target data should be 1-dimensional.")
def infer(self, x, **fit_params):
"""Perform an inference step
The first output of the ``module`` must be a single array that
has either shape (n,) or shape (n, 1). In the latter case, the
output will be reshaped to become 1-dim.
"""
y_infer = super().infer(x, **fit_params)
rest = None
if isinstance(y_infer, tuple):
y_infer, *rest = y_infer
if (y_infer.dim() > 2) or ((y_infer.dim() == 2) and (y_infer.shape[1] != 1)):
raise ValueError(
"Expected module output to have shape (n,) or "
"(n, 1), got {} instead".format(tuple(y_infer.shape)))
y_infer = y_infer.reshape(-1)
if rest is None:
return y_infer
return (y_infer,) + tuple(rest)
# pylint: disable=signature-differs
def fit(self, X, y, **fit_params):
"""See ``NeuralNet.fit``.
In contrast to ``NeuralNet.fit``, ``y`` is non-optional to
avoid mistakenly forgetting about ``y``. However, ``y`` can be
set to ``None`` in case it is derived dynamically from
``X``.
"""
# pylint: disable=useless-super-delegation
# this is actually a pylint bug:
# https://github.com/PyCQA/pylint/issues/1085
return super().fit(X, y, **fit_params)
def predict(self, X):
"""Where applicable, return class labels for samples in X.
If the module's forward method returns multiple outputs as a
tuple, it is assumed that the first output contains the
relevant information and the other values are ignored. If all
values are relevant, consider using
:func:`~skorch.NeuralNet.forward` instead.
Parameters
----------
X : input data, compatible with skorch.dataset.Dataset
By default, you should be able to pass:
* numpy arrays
* torch tensors
* pandas DataFrame or Series
* scipy sparse CSR matrices
* a dictionary of the former three
* a list/tuple of the former three
* a Dataset
If this doesn't work with your data, you have to pass a
``Dataset`` that can deal with the data.
Returns
-------
y_pred : numpy ndarray
"""
y_proba = self.predict_proba(X)
return (y_proba[:, 1] > self.threshold).astype('uint8')