-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathmodel.py
1854 lines (1557 loc) · 84.8 KB
/
model.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Copyright (c) 2022 Poutyne and all respective contributors.
Each contributor holds copyright over their respective contributions. The project versioning (Git)
records all such contribution source information.
This file is part of Poutyne.
Poutyne is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
version.
Poutyne 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with Poutyne. If not, see
<https://www.gnu.org/licenses/>.
"""
# pylint: disable=too-many-lines,too-many-public-methods
import contextlib
import numbers
import timeit
import warnings
from collections import defaultdict
from typing import Iterable, Mapping, List, Union, Any, Tuple
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.nn.utils.rnn import PackedSequence
from torch.utils.data import DataLoader
from poutyne import torch_to_numpy, numpy_to_torch, torch_to
from .callbacks import CallbackList, ProgressionCallback, Callback
from .iterators import EpochIterator, _get_step_iterator, StepIterator
from .metrics import get_epoch_metric
from .metrics import get_loss_or_metric, get_callables_and_names, rename_doubles, flatten_metric_names
from .optimizers import get_optimizer
from .warning_manager import warning_settings
from ..utils import TensorDataset, _concat
class Model:
"""
The Model class encapsulates a PyTorch network, a PyTorch optimizer, a loss function and
metric functions. It allows the user to train a neural network without hand-coding the
epoch/step logic.
Args:
network (torch.nn.Module): A PyTorch network.
optimizer (Union[torch.optim.Optimizer, str, dict]): If torch.optim.Optimier, an initialized PyTorch.
If str, should be the name of the optimizer in Pytorch (i.e. 'Adam' for torch.optim.Adam).
If dict, should contain a key ``'optim'`` with the value be the name of the optimizer; other
entries are passed to the optimizer as keyword arguments.
(Default value = None)
loss_function(Union[Callable, str]) It can be any PyTorch loss layer or custom loss function. It
can also be a string with the same name as a PyTorch loss function (either the functional or
object name). The loss function must have the signature ``loss_function(input, target)`` where
``input`` is the prediction of the network and ``target`` is the ground truth.
(Default value = None)
batch_metrics (list): List of functions with the same signature as the loss function. Each metric
can be any PyTorch loss function. It can also be a string with the same name as a PyTorch
loss function (either the functional or object name). Furthermore, see :ref:`batch metrics`
for supplementary available batch metrics. 'accuracy' (or just 'acc') is an often used metric.
Each metric function is called on each batch of the optimization and on the validation batches
at the end of the epoch.
(Default value = None)
epoch_metrics (list): List of objects with the same signature as either :class:`~poutyne.EpochMetric` or
:class:`torchmetrics.Metric <torchmetrics.Metric>`.
See :ref:`epoch metrics` and the
`TorchMetrics documentation <https://torchmetrics.readthedocs.io/en/latest/references/modules.html>`__ for
available epoch metrics.
(Default value = None)
torch_metrics (list): List of `TorchMetrics <https://torchmetrics.readthedocs.io/>`__ objects.
List of objects with the same signature as :class:`torchmetrics.Metric <torchmetrics.Metric>`.
See `TorchMetrics documentation <https://torchmetrics.readthedocs.io/en/latest/references/modules.html>`__
for available torch metrics. (Default value = None)
.. warning:: When using this argument, the torch metrics are computed at each batch. This
can significantly slow down the compuations depending on the metrics used. In such case, we advise to
use them as epoch metrics instead.
device (Union[torch.torch.device, List[torch.torch.device]]): The device to which the network is
sent or the list of device to which the network is sent. See :func:`~Model.to()` for details.
Note:
The name of each batch and epoch metric can be change by passing a tuple ``(name, metric)`` instead
of simply the metric function or object, where ``name`` is the alternative name of the metric.
Batch and epoch metrics can return multiple metrics (e.g. an epoch metric could return an F1-score
with the associated precision and recall). See :ref:`multiple metrics at once` for more details.
Attributes:
network (torch.nn.Module): The associated PyTorch network.
optimizer (torch.optim.Optimizer): The associated PyTorch optimizer.
loss_function: The associated loss function.
batch_metrics (list): The associated metric functions for every batch.
epoch_metrics (list): The associated metric functions for every epoch.
Examples:
Using Numpy arrays (or tensors) dataset::
from poutyne import Model
import torch
import numpy as np
num_features = 20
num_classes = 5
# Our training dataset with 800 samples.
num_train_samples = 800
train_x = np.random.randn(num_train_samples, num_features).astype('float32')
train_y = np.random.randint(num_classes, size=num_train_samples).astype('int64')
# Our validation dataset with 200 samples.
num_valid_samples = 200
valid_x = np.random.randn(num_valid_samples, num_features).astype('float32')
valid_y = np.random.randint(num_classes, size=num_valid_samples).astype('int64')
pytorch_network = torch.nn.Linear(num_features, num_classes) # Our network
# We create and optimize our model
model = Model(pytorch_network, 'sgd', 'cross_entropy', batch_metrics=['accuracy'])
model.fit(train_x, train_y,
validation_data=(valid_x, valid_y),
epochs=5,
batch_size=32)
.. code-block:: none
Epoch 1/5 0.02s Step 25/25: loss: 1.719885, acc: 19.375000, val_loss: 1.667446, val_acc: 22.000000
Epoch 2/5 0.02s Step 25/25: loss: 1.705489, acc: 19.750000, val_loss: 1.660806, val_acc: 22.000000
Epoch 3/5 0.01s Step 25/25: loss: 1.692345, acc: 19.625000, val_loss: 1.655008, val_acc: 22.500000
...
Using PyTorch DataLoader::
import torch
from torch.utils.data import DataLoader, TensorDataset
from poutyne import Model
num_features = 20
num_classes = 5
# Our training dataset with 800 samples.
num_train_samples = 800
train_x = torch.rand(num_train_samples, num_features)
train_y = torch.randint(num_classes, (num_train_samples,), dtype=torch.long)
train_dataset = TensorDataset(train_x, train_y)
train_generator = DataLoader(train_dataset, batch_size=32)
# Our validation dataset with 200 samples.
num_valid_samples = 200
valid_x = torch.rand(num_valid_samples, num_features)
valid_y = torch.randint(num_classes, (num_valid_samples,), dtype=torch.long)
valid_dataset = TensorDataset(valid_x, valid_y)
valid_generator = DataLoader(valid_dataset, batch_size=32)
pytorch_network = torch.nn.Linear(num_features, num_train_samples)
model = Model(pytorch_network, 'sgd', 'cross_entropy', batch_metrics=['accuracy'])
model.fit_generator(train_generator,
valid_generator,
epochs=5)
.. code-block:: none
Epoch 1/5 0.05s Step 25/25: loss: 6.752676, acc: 0.000000, val_loss: 6.575071, val_acc: 0.000000
Epoch 2/5 0.03s Step 25/25: loss: 6.454859, acc: 0.125000, val_loss: 6.279577, val_acc: 0.000000
Epoch 3/5 0.03s Step 25/25: loss: 6.158523, acc: 2.125000, val_loss: 5.985811, val_acc: 9.500000
...
"""
def __init__(
self,
network,
optimizer,
loss_function,
*,
batch_metrics=None,
epoch_metrics=None,
torch_metrics=None,
device=None,
):
if not isinstance(network, nn.Module):
raise ValueError(f"network should be of type derived from nn.Module, received {type(network)}.")
if optimizer is not None and not isinstance(optimizer, (optim.Optimizer, str, dict)):
raise ValueError(f"optimizer should be of type derived from optim.Optimizer, received {type(optimizer)}.")
batch_metrics = [] if batch_metrics is None else batch_metrics
epoch_metrics = [] if epoch_metrics is None else epoch_metrics
torch_metrics = [] if torch_metrics is None else torch_metrics
self.network = network
self.optimizer = get_optimizer(optimizer, self.network)
self.loss_function = get_loss_or_metric(loss_function)
if isinstance(self.loss_function, tuple):
self.loss_function = self.loss_function[1]
self._check_network_optimizer_parameters_match()
self._set_metrics_attributes(batch_metrics, epoch_metrics, torch_metrics)
self.device = None
self.other_device = None
if device is not None:
self.to(device)
def _check_network_optimizer_parameters_match(self):
if self.optimizer is not None:
param_set = set(self.network.parameters())
for param_group in self.optimizer.param_groups:
for param in param_group['params']:
if param not in param_set:
raise ValueError(
"All parameters in the optimizer should be part of the network. "
"This is so to insure that weights checkpointing and the likes "
"actually consider all parameters."
)
def _set_metrics_attributes(self, batch_metrics, epoch_metrics, torch_metrics):
batch_metrics = list(map(get_loss_or_metric, batch_metrics))
self.batch_metrics, batch_metrics_names = get_callables_and_names(batch_metrics)
epoch_metrics = list(map(get_epoch_metric, epoch_metrics))
self.epoch_metrics, epoch_metrics_names = get_callables_and_names(epoch_metrics)
self.torch_metrics, torch_metrics_names = get_callables_and_names(torch_metrics)
self.original_batch_metrics_names, self.original_epoch_metrics_names, self.original_torch_metrics_names = (
batch_metrics_names,
epoch_metrics_names,
torch_metrics_names,
)
batch_metrics_names, epoch_metrics_names, torch_metrics_names = rename_doubles(
batch_metrics_names, epoch_metrics_names, torch_metrics_names
)
self.unflatten_batch_metrics_names = batch_metrics_names
self.unflatten_epoch_metrics_names = epoch_metrics_names
self.unflatten_torch_metrics_names = torch_metrics_names
self.batch_metrics_names = flatten_metric_names(batch_metrics_names)
self.epoch_metrics_names = flatten_metric_names(epoch_metrics_names)
self.torch_metrics_names = flatten_metric_names(torch_metrics_names)
self.metrics_names = self.batch_metrics_names + self.epoch_metrics_names + self.torch_metrics_names
@contextlib.contextmanager
def _set_training_mode(self, training):
old_training = self.network.training
self.network.train(training)
with torch.set_grad_enabled(training):
yield
self.network.train(old_training)
def fit(
self,
x,
y,
validation_data=None,
*,
batch_size=32,
epochs=1000,
steps_per_epoch=None,
validation_steps=None,
batches_per_step=1,
initial_epoch=1,
verbose=True,
progress_options: Union[dict, None] = None,
callbacks=None,
dataloader_kwargs=None,
):
# pylint: disable=line-too-long,too-many-locals
"""
Trains the network on a dataset. This method creates generators and calls
the :func:`~Model.fit_generator()` method.
Args:
x (Union[~torch.Tensor, ~numpy.ndarray] or Union[tuple, list] of Union[~torch.Tensor, ~numpy.ndarray]):
Training dataset. Union[Tensor, ndarray] if the model has a single input.
Union[tuple, list] of Union[Tensor, ndarray] if the model has multiple inputs.
y (Union[~torch.Tensor, ~numpy.ndarray] or Union[tuple, list] of Union[~torch.Tensor, ~numpy.ndarray]):
Target. Union[Tensor, ndarray] if the model has a single output.
Union[tuple, list] of Union[Tensor, ndarray] if the model has multiple outputs.
validation_data (Tuple[``x_val``, ``y_val``]):
Same format as ``x`` and ``y`` previously described. Validation dataset on which to
evaluate the loss and any model metrics at the end of each epoch. The model will not be
trained on this data.
(Default value = None)
batch_size (int): Number of samples given to the network at one time.
(Default value = 32)
epochs (int): Number of times the entire training dataset is seen.
(Default value = 1000)
steps_per_epoch (int, optional): Number of batch used during one epoch. Obviously, using
this argument may cause one epoch not to see the entire training dataset or see it
multiple times.
(Defaults the number of steps needed to see the entire training dataset)
validation_steps (int, optional): Same as for ``steps_per_epoch`` but for the validation
dataset.
(Defaults to the number of steps needed to see the entire validation dataset)
batches_per_step (int): Number of batches on which to compute the running loss before
backpropagating it through the network. Note that the total loss used for backpropagation is
the mean of the `batches_per_step` batch losses.
(Default value = 1)
initial_epoch (int, optional): Epoch at which to start training
(useful for resuming a previous training run).
(Default value = 1)
verbose (bool): Whether to display the progress of the training.
(Default value = True)
progress_options (dict, optional): Keyword arguments to pass to the default progression callback used
in Poutyne (See :class:`~poutyne.ProgressionCallback` for the available arguments).
(Default value = None)
callbacks (List[~poutyne.Callback]): List of callbacks that will be called
during training.
(Default value = None)
dataloader_kwargs (dict, optional): Keyword arguments to pass to the PyTorch dataloaders created
internally. By default, ``shuffle=True`` is passed for the training dataloader but this can be
overridden by using this argument.
Returns:
List of dict containing the history of each epoch.
Example:
.. code-block:: python
model = Model(pytorch_network, optimizer, loss_function)
history = model.fit(train_x, train_y,
validation_data=(valid_x, valid_y)
epochs=num_epochs,
batch_size=batch_size,
verbose=False)
print(*history, sep="\\n")
.. code-block:: python
{'epoch': 1, 'loss': 1.7198852968215943, 'time': 0.019999928001197986, 'acc': 19.375, 'val_loss': 1.6674459838867188, 'val_acc': 22.0}
{'epoch': 2, 'loss': 1.7054892110824584, 'time': 0.015421080999658443, 'acc': 19.75, 'val_loss': 1.660806336402893, 'val_acc': 22.0}
{'epoch': 3, 'loss': 1.6923445892333984, 'time': 0.01363091799794347, 'acc': 19.625, 'val_loss': 1.6550078630447387, 'val_acc': 22.5}
...
"""
train_dataset = self._dataset_from_data((x, y))
valid_dataset = None
if validation_data is not None:
valid_dataset = self._dataset_from_data(validation_data)
return self.fit_dataset(
train_dataset,
valid_dataset=valid_dataset,
epochs=epochs,
batch_size=batch_size,
steps_per_epoch=steps_per_epoch,
validation_steps=validation_steps,
batches_per_step=batches_per_step,
initial_epoch=initial_epoch,
verbose=verbose,
progress_options=progress_options,
callbacks=callbacks,
dataloader_kwargs=dataloader_kwargs,
)
def _dataset_from_data(self, args):
args = numpy_to_torch(args)
return TensorDataset(*args) if len(args) > 1 else args[0]
def fit_dataset(
self,
train_dataset,
valid_dataset=None,
*,
batch_size=32,
epochs=1000,
steps_per_epoch=None,
validation_steps=None,
batches_per_step=1,
initial_epoch=1,
verbose=True,
progress_options=None,
callbacks=None,
num_workers=0,
collate_fn=None,
dataloader_kwargs=None,
):
# pylint: disable=line-too-long,too-many-locals
"""
Trains the network on a dataset. This method creates dataloaders and calls the
:func:`~Model.fit_generator()` method.
Args:
train_dataset (~torch.utils.data.Dataset): Training dataset.
valid_dataset (~torch.utils.data.Dataset): Validation dataset.
batch_size (int): Number of samples given to the network at one time.
(Default value = 32)
epochs (int): Number of times the entire training dataset is seen.
(Default value = 1000)
steps_per_epoch (int, optional): Number of batch used during one epoch. Obviously, using
this argument may cause one epoch not to see the entire training dataset or see it
multiple times.
(Defaults the number of steps needed to see the entire training dataset)
validation_steps (int, optional): Same as for ``steps_per_epoch`` but for the validation
dataset.
(Defaults to the number of steps needed to see the entire validation dataset)
batches_per_step (int): Number of batches on which to compute the running loss before
backpropagating it through the network. Note that the total loss used for backpropagation is
the mean of the `batches_per_step` batch losses.
(Default value = 1)
initial_epoch (int, optional): Epoch at which to start training
(useful for resuming a previous training run).
(Default value = 1)
verbose (bool): Whether to display the progress of the training.
(Default value = True)
progress_options (dict, optional): Keyword arguments to pass to the default progression callback used
in Poutyne (See :class:`~poutyne.ProgressionCallback` for the available arguments).
(Default value = None)
callbacks (List[~poutyne.Callback]): List of callbacks that will be called
during training.
(Default value = None)
dataloader_kwargs (dict, optional): Keyword arguments to pass to the PyTorch dataloaders created
internally. By default, ``shuffle=True`` is passed for the training dataloader but this can be
overridden by using this argument.
num_workers (int, optional): how many subprocesses to use for data loading.
``0`` means that the data will be loaded in the main process.
(Default value = 0)
collate_fn (Callable, optional): merges a list of samples to form a mini-batch of Tensor(s).
Used when using batched loading from a map-style dataset.
Returns:
List of dict containing the history of each epoch.
See :class:`~torch.utils.data.DataLoader` for details on ``batch_size``, ``num_workers`` and ``collate_fn``.
Example:
.. code-block:: python
model = Model(pytorch_network, optimizer, loss_function)
history = model.fit(train_dataset,
valid_dataset,
epochs=num_epochs,
batch_size=batch_size,
verbose=False)
print(*history, sep="\\n")
.. code-block:: python
{'epoch': 1, 'loss': 1.7198852968215943, 'time': 0.019999928001197986, 'acc': 19.375, 'val_loss': 1.6674459838867188, 'val_acc': 22.0}
{'epoch': 2, 'loss': 1.7054892110824584, 'time': 0.015421080999658443, 'acc': 19.75, 'val_loss': 1.660806336402893, 'val_acc': 22.0}
{'epoch': 3, 'loss': 1.6923445892333984, 'time': 0.01363091799794347, 'acc': 19.625, 'val_loss': 1.6550078630447387, 'val_acc': 22.5}
...
"""
if dataloader_kwargs is None:
dataloader_kwargs = {}
dataloader_kwargs = {
'batch_size': batch_size,
'num_workers': num_workers,
'collate_fn': collate_fn,
**dataloader_kwargs,
}
train_generator = DataLoader(train_dataset, **{'shuffle': True, **dataloader_kwargs})
valid_generator = None
if valid_dataset is not None:
valid_generator = DataLoader(valid_dataset, **dataloader_kwargs)
return self.fit_generator(
train_generator,
valid_generator=valid_generator,
epochs=epochs,
steps_per_epoch=steps_per_epoch,
validation_steps=validation_steps,
batches_per_step=batches_per_step,
initial_epoch=initial_epoch,
verbose=verbose,
progress_options=progress_options,
callbacks=callbacks,
)
def fit_generator(
self,
train_generator,
valid_generator=None,
*,
epochs=1000,
steps_per_epoch=None,
validation_steps=None,
batches_per_step=1,
initial_epoch=1,
verbose=True,
progress_options: Union[dict, None] = None,
callbacks=None,
):
# pylint: disable=line-too-long
"""
Trains the network on a dataset using a generator.
Args:
train_generator: Generator-like object for the training dataset. The generator must
yield a batch in the form of a tuple (x, y) where ``x`` is the input and ``y`` is the
target. The batch size is inferred from ``x`` and ``y``. See :func:`get_batch_size()` for
details on the inferring algorithm. The loss and the metrics are averaged using this
batch size. If the batch size cannot be inferred then a warning is raised and the
"batch size" defaults to 1.
If the generator does not have a method ``__len__()``, either the ``steps_per_epoch``
argument must be provided, or the iterator returned raises a StopIteration exception at
the end of the training dataset. PyTorch DataLoaders object do provide a ``__len__()``
method.
Before each epoch, the method ``__iter__()`` on the generator is called and the method
``__next__()`` is called for each step on resulting object returned by ``__iter__()``.
Notice that a call to ``__iter__()`` on a generator made using the python keyword
``yield`` returns the generator itself.
valid_generator (optional): Generator-like object for the validation dataset. This generator
is optional. The generator is used the same way as the generator ``train_generator``. If
the generator does not have a method ``__len__()``, either the ``validation_steps`` or the
``steps_per_epoch`` argument must be provided or the iterator returned raises a StopIteration
exception at the end of the validation dataset.
(Default value = None)
epochs (int): Number of times the entire training dataset is seen.
(Default value = 1000)
steps_per_epoch (int, optional): Number of batch used during one epoch. Obviously, using this
argument may cause one epoch not to see the entire training dataset or see it multiple times.
See argument ``train_generator`` and ``valid_generator`` for more details of how
``steps_per_epoch`` is used.
validation_steps (int, optional): Same as for ``steps_per_epoch`` but for the validation dataset.
See argument ``valid_generator`` for more details of how ``validation_steps`` is used.
batches_per_step (int): Number of batches on which to compute the running loss before
backpropagating it through the network. Note that the total loss used for backpropagation is
the mean of the `batches_per_step` batch losses.
(Default value = 1)
initial_epoch (int, optional): Epoch at which to start training (useful for resuming a previous
training run).
(Default value = 1)
verbose (bool): Whether to display the progress of the training.
(Default value = True)
progress_options (dict, optional): Keyword arguments to pass to the default progression callback used
in Poutyne (See :class:`~poutyne.ProgressionCallback` for the available arguments).
(Default value = None, meaning default color setting and progress bar)
callbacks (List[~poutyne.Callback]): List of callbacks that will be called during
training. (Default value = None)
Returns:
List of dict containing the history of each epoch.
Example:
.. code-block:: python
model = Model(pytorch_network, optimizer, loss_function)
history = model.fit_generator(train_generator,
valid_generator,
epochs=num_epochs,
verbose=False)
print(*history, sep="\\n")
.. code-block:: python
{'epoch': 1, 'loss': 1.7198852968215943, 'time': 0.019999928001197986, 'acc': 19.375, 'val_loss': 1.6674459838867188, 'val_acc': 22.0}
{'epoch': 2, 'loss': 1.7054892110824584, 'time': 0.015421080999658443, 'acc': 19.75, 'val_loss': 1.660806336402893, 'val_acc': 22.0}
{'epoch': 3, 'loss': 1.6923445892333984, 'time': 0.01363091799794347, 'acc': 19.625, 'val_loss': 1.6550078630447387, 'val_acc': 22.5}
...
"""
if self.optimizer is None:
raise ValueError("Impossible to fit when optimizer is None.")
self._transfer_optimizer_state_to_right_device()
callbacks = [] if callbacks is None else callbacks
if verbose:
progress_options = {} if progress_options is None else progress_options
callbacks = [ProgressionCallback(**progress_options)] + callbacks
callback_list = CallbackList(callbacks)
callback_list.set_model(self)
self.stop_training = False
epoch_iterator = EpochIterator(
self,
train_generator,
valid_generator,
epochs=epochs,
steps_per_epoch=steps_per_epoch,
validation_steps=validation_steps,
initial_epoch=initial_epoch,
callback=callback_list,
batch_metrics_names=self.batch_metrics_names,
epoch_metrics_names=self.epoch_metrics_names,
torch_metrics_names=self.torch_metrics_names,
)
if batches_per_step > 1:
self._fit_generator_n_batches_per_step(epoch_iterator, callback_list, batches_per_step)
else:
self._fit_generator_one_batch_per_step(epoch_iterator, callback_list)
return epoch_iterator.epoch_logs
def _fit_generator_n_batches_per_step(self, epoch_iterator, callback_list, batches_per_step):
for train_step_iterator, valid_step_iterator in epoch_iterator:
examples_in_step = 0
with self._set_training_mode(True):
for step, (x, y) in train_step_iterator:
step.size = self.get_batch_size(x, y)
examples_in_step += step.size
(
step.loss,
step.batch_metrics,
step.torch_metrics,
did_backprop,
_,
) = self._fit_batch_n_batches_per_step(
x, y, batches_per_step, examples_in_step, callback=callback_list, step=step
)
if did_backprop:
examples_in_step = 0
if not did_backprop:
# Did not step after last batch
self._adjust_step_size(examples_in_step)
self.optimizer.step()
train_step_iterator.epoch_metrics = self._get_epoch_metrics()
train_step_iterator.torch_metrics = self._get_torch_metrics()
self._run_validation(valid_step_iterator, callback_list)
def _fit_batch_n_batches_per_step(
self,
x,
y,
batches_per_step,
examples_in_step,
*,
callback=Callback(),
step=None,
return_pred=False,
convert_to_numpy=True,
):
# pylint: disable=too-many-locals
zero_all_gradients = (step.number - 1) % batches_per_step == 0
do_backprop = step.number % batches_per_step == 0
if zero_all_gradients:
self.optimizer.zero_grad()
loss_tensor, batch_metrics, torch_metrics, pred_y = self._compute_loss_and_metrics(
x, y, return_loss_tensor=True, return_pred=return_pred, convert_to_numpy=convert_to_numpy
)
adjusted_loss_tensor = loss_tensor * step.size
adjusted_loss_tensor.backward()
callback.on_backward_end(step)
if do_backprop:
self._adjust_step_size(examples_in_step)
self.optimizer.step()
loss = float(loss_tensor)
return loss, batch_metrics, torch_metrics, do_backprop, pred_y
def _fit_generator_one_batch_per_step(self, epoch_iterator, callback_list):
for train_step_iterator, valid_step_iterator in epoch_iterator:
with self._set_training_mode(True):
for step, (x, y) in train_step_iterator:
step.loss, step.batch_metrics, step.torch_metrics, _ = self._fit_batch(
x, y, callback=callback_list, step=step.number
)
step.size = self.get_batch_size(x, y)
train_step_iterator.epoch_metrics = self._get_epoch_metrics()
train_step_iterator.torch_metrics = self._get_torch_metrics()
self._run_validation(valid_step_iterator, callback_list)
def _fit_batch(self, x, y, *, callback=Callback(), step=None, return_pred=False, convert_to_numpy=True):
self.optimizer.zero_grad()
loss_tensor, batch_metrics, torch_metrics, pred_y = self._compute_loss_and_metrics(
x, y, return_loss_tensor=True, return_pred=return_pred, convert_to_numpy=convert_to_numpy
)
loss_tensor.backward()
callback.on_backward_end(step)
self.optimizer.step()
loss = float(loss_tensor)
return loss, batch_metrics, torch_metrics, pred_y
def _run_validation(self, valid_step_iterator, callback_list):
if valid_step_iterator is not None:
valid_begin_time = timeit.default_timer()
callback_list.on_valid_begin({})
self._validate(valid_step_iterator)
valid_step_iterator.epoch_metrics = self._get_epoch_metrics()
valid_step_iterator.torch_metrics = self._get_torch_metrics()
valid_total_time = timeit.default_timer() - valid_begin_time
valid_metrics_log = {'time': valid_total_time}
valid_metrics_log.update(valid_step_iterator.metrics_logs)
callback_list.on_valid_end(valid_metrics_log)
def _adjust_step_size(self, examples_in_step):
for param in self.network.parameters():
if param.grad is not None:
param.grad /= examples_in_step
def _process_input(self, *args):
args = numpy_to_torch(args)
if self.device is not None:
args = torch_to(args, self.device)
return args[0] if len(args) == 1 else args
def preprocess_input(self, x, y=None):
if y is not None:
x, y = self._process_input(x, y)
else:
x = self._process_input(x)
x = x if isinstance(x, (tuple, list)) else (x,)
# We return PackedSequence in a tuple since it is a namedtuple, thus an iterator object and
# would break later when we call self.network(*x) since it will iterate over the PackedSequence named attribute.
x = (x,) if isinstance(x, PackedSequence) else x
return (x, y) if y is not None else x
def train_on_batch(self, x, y, *, return_pred=False, return_dict_format=False, convert_to_numpy=True):
"""
Trains the network for the batch ``(x, y)`` and computes the loss and the metrics, and
optionally returns the predictions.
Args:
x: Input data as a batch.
y: Target data as a batch.
return_pred (bool, optional): Whether to return the predictions.
(Default value = False)
return_dict_format (bool, optional): Whether to return the loss and metrics in a dict format or not.
(Default value = False)
convert_to_numpy (bool, optional): Whether to convert the predictions into Numpy Arrays when ``return_pred``
is true. (Default value = True)
Returns:
Float ``loss`` if no metrics were specified and ``return_pred`` is false.
Otherwise, tuple ``(loss, metrics)`` if ``return_pred`` is false.
``metrics`` is a Numpy array of size ``n``, where ``n`` is the
number of metrics if ``n > 1``. If ``n == 1``, then ``metrics`` is a
float. If ``n == 0``, the ``metrics`` is omitted.
Tuple ``(loss, metrics, pred_y)`` if ``return_pred`` is true where
``pred_y`` is the predictions with tensors converted into Numpy
arrays.
If ``return_dict_format`` is True, then ``loss, metrics`` are replaced by a
dictionary.
"""
if self.optimizer is None:
raise ValueError("Impossible to fit when optimizer is None.")
with self._set_training_mode(True):
self._transfer_optimizer_state_to_right_device()
loss, batch_metrics, torch_metrics, pred_y = self._fit_batch(
x, y, return_pred=return_pred, convert_to_numpy=convert_to_numpy
)
if return_dict_format:
logs = dict(loss=loss)
logs.update(zip(self.batch_metrics_names, batch_metrics))
logs.update(zip(self.torch_metrics_names, torch_metrics))
return self._format_truth_pred_return((logs,), pred_y, return_pred)
metrics = np.concatenate((batch_metrics, torch_metrics))
return self._format_loss_metrics_return(loss, metrics, pred_y, return_pred)
def _format_loss_metrics_return(self, loss, metrics, pred_y, return_pred, true_y=None, return_ground_truth=False):
# pylint: disable=too-many-arguments
ret = (loss,)
ret += tuple(metrics.tolist()) if len(metrics) <= 1 else (metrics,)
return self._format_truth_pred_return(ret, pred_y, return_pred, true_y, return_ground_truth)
def _format_truth_pred_return(self, init, pred_y, return_pred, true_y=None, return_ground_truth=False):
# pylint: disable=too-many-arguments
if return_pred:
init += (pred_y,)
if return_ground_truth:
init += (true_y,)
return init[0] if len(init) == 1 else init
def predict(
self,
x,
*,
batch_size=32,
convert_to_numpy=True,
verbose=True,
progress_options: Union[dict, None] = None,
callbacks=None,
dataloader_kwargs=None,
) -> Any:
"""
Returns the predictions of the network given a dataset ``x``, where the tensors are
converted into Numpy arrays.
Args:
x (Union[~torch.Tensor, ~numpy.ndarray] or Union[tuple, list] of Union[~torch.Tensor, ~numpy.ndarray]):
Input to the model. Union[Tensor, ndarray] if the model has a single input.
Union[tuple, list] of Union[Tensor, ndarray] if the model has multiple inputs.
batch_size (int): Number of samples given to the network at one time.
(Default value = 32)
concatenate_returns (bool, optional): Whether to concatenate the predictions when returning them.
(Default value = True)
verbose (bool): Whether to display the progress of the evaluation.
(Default value = True)
progress_options (dict, optional): Keyword arguments to pass to the default progression callback used
in Poutyne (See :class:`~poutyne.ProgressionCallback` for the available arguments).
(Default value = None, meaning default color setting and progress bar)
callbacks (List[~poutyne.Callback]): List of callbacks that will be called during
testing. (Default value = None)
dataloader_kwargs (dict, optional): Keyword arguments to pass to the PyTorch dataloaders created
internally.
Returns:
Return the predictions in the format outputted by the model.
"""
x = x if isinstance(x, (tuple, list)) else (x,)
dataset = self._dataset_from_data(x)
return self.predict_dataset(
dataset,
batch_size=batch_size,
concatenate_returns=True,
convert_to_numpy=convert_to_numpy,
dataloader_kwargs=dataloader_kwargs,
verbose=verbose,
progress_options=progress_options,
callbacks=callbacks,
)
def predict_dataset(
self,
dataset,
*,
batch_size=32,
steps=None,
has_ground_truth=False,
return_ground_truth=False,
concatenate_returns=True,
convert_to_numpy=True,
num_workers=0,
collate_fn=None,
verbose=True,
progress_options: Union[dict, None] = None,
callbacks=None,
dataloader_kwargs=None,
) -> Any:
"""
Returns the predictions of the network given a dataset ``x``, where the tensors are
converted into Numpy arrays.
Args:
dataset (~torch.utils.data.Dataset): Dataset. Must not return ``y``, just ``x``, unless
`has_ground_truth` is true.
batch_size (int): Number of samples given to the network at one time.
(Default value = 32)
steps (int, optional): Number of iterations done on ``generator``.
(Defaults the number of steps needed to see the entire dataset)
has_ground_truth (bool, optional): Whether the generator yields the target ``y``. Automatically
set to true if `return_ground_truth` is true. (Default value = False)
return_ground_truth (bool, optional): Whether to return the ground truths. If true, automatically
set `has_ground_truth` to true. (Default value = False)
concatenate_returns (bool, optional): Whether to concatenate the predictions
or the ground truths when returning them. See :func:`predict_generator()`
for details. (Default value = True)
concatenate_returns (bool, optional): Whether to concatenate the predictions
or the ground truths when returning them. (Default value = True)
num_workers (int, optional): how many subprocesses to use for data loading.
``0`` means that the data will be loaded in the main process.
(Default value = 0)
collate_fn (Callable, optional): merges a list of samples to form a mini-batch of Tensor(s).
Used when using batched loading from a map-style dataset.
verbose (bool): Whether to display the progress of the evaluation.
(Default value = True)
progress_options (dict, optional): Keyword arguments to pass to the default progression callback used
in Poutyne (See :class:`~poutyne.ProgressionCallback` for the available arguments).
(Default value = None, meaning default color setting and progress bar)
callbacks (List[~poutyne.Callback]): List of callbacks that will be called during
testing. (Default value = None)
dataloader_kwargs (dict, optional): Keyword arguments to pass to the PyTorch dataloaders created
internally.
Returns:
Depends on the value of ``concatenate_returns``. By default, (``concatenate_returns`` is true),
the data structures (tensor, tuple, list, dict) returned as predictions for the batches are
merged together. In the merge, the tensors are converted into Numpy arrays and are then
concatenated together. If ``concatenate_returns`` is false, then a list of the predictions
for the batches is returned with tensors converted into Numpy arrays.
See:
:class:`~torch.utils.data.DataLoader` for details on ``batch_size``, ``num_workers`` and ``collate_fn``.
"""
if dataloader_kwargs is None:
dataloader_kwargs = {}
dataloader_kwargs = {
'batch_size': batch_size,
'num_workers': num_workers,
'collate_fn': collate_fn,
**dataloader_kwargs,
}
generator = DataLoader(dataset, **dataloader_kwargs)
return self.predict_generator(
generator,
steps=steps,
has_ground_truth=has_ground_truth,
return_ground_truth=return_ground_truth,
concatenate_returns=concatenate_returns,
convert_to_numpy=convert_to_numpy,
verbose=verbose,
progress_options=progress_options,
callbacks=callbacks,
)
def predict_generator(
self,
generator,
*,
steps=None,
has_ground_truth=False,
return_ground_truth=False,
concatenate_returns=True,
convert_to_numpy=True,
verbose=True,
progress_options: Union[dict, None] = None,
callbacks=None,
) -> Any:
"""
Returns the predictions of the network given batches of samples ``x``, where the tensors are
converted into Numpy arrays.
Args:
generator: Generator-like object for the dataset. The generator must yield a batch of
samples. See the :func:`fit_generator()` method for details on the types of generators
supported. This should only yield input data ``x`` and NOT the target ``y``, unless
`has_ground_truth` is true.
steps (int, optional): Number of iterations done on ``generator``.
(Defaults the number of steps needed to see the entire dataset)
has_ground_truth (bool, optional): Whether the generator yields the target ``y``. Automatically
set to true if `return_ground_truth` is true. (Default value = False)
return_ground_truth (bool, optional): Whether to return the ground truths. If true, automatically
set `has_ground_truth` to true. (Default value = False)
concatenate_returns (bool, optional): Whether to concatenate the predictions
or the ground truths when returning them. (Default value = True)
convert_to_numpy (bool, optional): Whether to convert the predictions or ground truths into Numpy Arrays.
(Default value = True)
verbose (bool): Whether to display the progress of the evaluation.
(Default value = True)
progress_options (dict, optional): Keyword arguments to pass to the default progression callback used
in Poutyne (See :class:`~poutyne.ProgressionCallback` for the available arguments).
(Default value = None, meaning default color setting and progress bar)
callbacks (List[~poutyne.Callback]): List of callbacks that will be called during
testing. (Default value = None)
Returns:
Depends on the value of ``concatenate_returns``. By default, (``concatenate_returns`` is true),
the data structures (tensor, tuple, list, dict) returned as predictions for the batches are
merged together. In the merge, the tensors are converted into Numpy arrays and are then
concatenated together. If ``concatenate_returns`` is false, then a list of the predictions
for the batches is returned with tensors converted into Numpy arrays.
"""
# pylint: disable=too-many-locals
has_ground_truth = has_ground_truth or return_ground_truth
if steps is None and hasattr(generator, '__len__'):
steps = len(generator)
pred_y = []
if return_ground_truth:
true_y = []
callbacks = [] if callbacks is None else callbacks
if verbose:
progress_options = {} if progress_options is None else progress_options