-
Notifications
You must be signed in to change notification settings - Fork 9
/
pt_model.py
1390 lines (1184 loc) · 48.2 KB
/
pt_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
"""PyTorch model wrapper."""
import contextlib
import logging
import os
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Literal,
Optional,
Sequence,
Union,
)
import numpy as np
import torch
from datasets import Dataset, DatasetDict
from datasets.combine import concatenate_datasets
from torch import nn
from torch.optim import Optimizer
from torch.optim.lr_scheduler import _LRScheduler as TorchLRScheduler
from torch.utils.data import DataLoader
from torch.utils.data import Dataset as TorchDataset
from cyclops.models.data import PTDataset
from cyclops.models.torch_utils import (
DefaultCriterion,
LossMeter,
get_device,
get_module,
)
from cyclops.models.utils import (
get_split,
is_pytorch_instance,
is_pytorch_model,
)
from cyclops.models.wrappers.base import ModelWrapper
from cyclops.models.wrappers.utils import (
DatasetColumn,
check_is_fitted,
set_random_seed,
to_numpy,
to_tensor,
)
from cyclops.utils.file import join, process_dir_save_path
from cyclops.utils.log import setup_logging
from cyclops.utils.optional import import_optional_module
if TYPE_CHECKING:
from monai.data.meta_tensor import MetaTensor
else:
MetaTensor = import_optional_module(
"monai.data.meta_tensor",
attribute="MetaTensor",
error="warn",
)
LOGGER = logging.getLogger(__name__)
setup_logging(print_level="INFO", logger=LOGGER)
# ruff: noqa: PLR0912
class PTModel(ModelWrapper):
"""PyTorch model wrapper.
Parameters
----------
model : nn.Module
A PyTorch model instance or class to wrap. If class, provide parameters
as kwargs in the format `model__<param_name>=<param_value>`.
criterion : str or torch.nn.Module, default=DefaultCriterion
The loss function to use. Accepts a string representing the name of a
PyTorch loss function as defined in `torch.nn.modules.loss` or a
`torch.nn.Module` instance/class. If class, provide parameters as kwargs
in the format `criterion__<param_name>=<param_value>`.
default criterion is a placeholder that takes the mean value of logits.
optimizer : str or torch.optim.Optimizer, default=torch.optim.SGD
The optimizer to use. Accepts a string representing the name of a
PyTorch optimizer as defined in `torch.optim` or a `torch.optim.Optimizer`
instance/class. If class, provide parameters as kwargs in the format
`optimizer__<param_name>=<param_value>`.
lr : float, default=0.01
The learning rate to use.
lr_scheduler : str or torch.optim.lr_scheduler._LRScheduler, default="ConstantLR"
The learning rate scheduler to use. Accepts a string representing the name
of a PyTorch learning rate scheduler as defined in `torch.optim.lr_scheduler`
or a `torch.optim.lr_scheduler._LRScheduler` instance/class. If class,
provide parameters as kwargs in the format
`lr_scheduler__<param_name>=<param_value>`.
lr_update_per_batch : bool, default=False
Whether to update the learning rate after each batch or after each epoch.
Set to `True` if using a learning rate scheduler that updates per batch
like `torch.optim.lr_scheduler.StepLR`.
batch_size : int, default=32
The batch size to use. Set to -1 for full batch.
max_epochs : int, default=10
The maximum number of epochs to train for.
activation : str or torch.nn.Module, default=nn.Identity
The activation function to use. Accepts a string representing the name of
a PyTorch activation function as defined in `torch.nn.modules.activation`
or a `torch.nn.Module` instance/class. If class, provide parameters as
kwargs in the format `activation__<param_name>=<param_value>`.
train_loader : torch.utils.data.DataLoader, default=torch.utils.data.DataLoader
An iterator for loading the training data in batches. The class assumes
it is a `torch.utils.data.DataLoader`. Arguments can be passed as kwargs
in the format `train_loader__<param_name>=<param_value>`.
test_loader : torch.utils.data.DataLoader, default=torch.utils.data.DataLoader
An iterator for loading the test/validation data in batches. The class
assumes it is a `torch.utils.data.DataLoader`. Arguments can be passed
as kwargs in the format `test_loader__<param_name>=<param_value>`.
num_workers : int, default=os.cpu_count()
The number of workers to use for loading the train/test data.
warm_start : bool, default=False
Whether to re-use the weights from the previous fit call. If `True`, the
model will continue training from the weights of the previous fit call.
save_every : int, default=-1
The number of epochs to train before saving the model. If it is a negative
only the latest model will be saved.
save_best_only : bool, default=True
Whether to save only the best model based on the validation loss.
device : str or torch.device, default="cpu"
The device to use for training.
seed : int, default=None
The random seed to use for reproducibility. If `None`, runs will be
stochastic.
deterministic : bool, default=False
Whether to use deterministic algorithms for training. This will make
runs reproducible but will be slower. It is ignored if `seed` is `None`.
concatenate_features : bool, default=True
Whether to concatenate the features in the dataset before passing them.
This is useful when the input is a Hugging Face Dataset and the features
are stored in different columns.
"""
def __init__(
self,
model: nn.Module,
criterion: Union[str, nn.Module] = DefaultCriterion,
optimizer: Union[str, Optimizer] = torch.optim.SGD,
lr: float = 0.01,
lr_scheduler: Optional[Union[str, TorchLRScheduler]] = "ConstantLR",
lr_update_per_batch: bool = False,
batch_size: int = 32,
max_epochs: int = 10,
activation: Optional[Union[str, nn.Module]] = nn.Identity,
train_loader=DataLoader,
test_loader=DataLoader,
num_workers=1,
warm_start: bool = False,
save_every: int = -1,
save_best_only: bool = True,
save_dir: Optional[str] = None,
device: Optional[Union[str, torch.device]] = None,
seed: Optional[int] = None,
deterministic: bool = False,
concatenate_features: bool = True,
**kwargs,
) -> None:
assert is_pytorch_model(
model,
), "`model` must be an instance or subclass of `torch.nn.Module`."
self.model = model
self.criterion = criterion
self.optimizer = optimizer
self.lr = lr
self.lr_scheduler = lr_scheduler
self.lr_update_per_batch = lr_update_per_batch
self.batch_size = batch_size
self.max_epochs = max_epochs
self.activation = activation
self.train_loader = train_loader
self.test_loader = test_loader
self.num_workers = num_workers
self.warm_start = warm_start
self.save_every = save_every
self.save_best_only = save_best_only
self.save_dir = save_dir
if device is None:
device = get_device()
self.device = device
self.seed = seed
self.deterministic = deterministic
self.concatenate_features = concatenate_features
vars(self).update(kwargs) # add any additional kwargs to the class
self.initialized_ = False
self.train_loss_ = LossMeter("train")
self.val_loss_ = LossMeter("val")
@property
def model_name(self) -> str:
"""The model name.
Returns
-------
str
The model name.
"""
return self.model_.__class__.__name__
def collect_params_for(self, prefix: str) -> Dict:
"""Collect parameters for a given prefix.
Parameters
----------
prefix : str
The prefix to collect parameters for.
Returns
-------
Dict
A dictionary of parameters for the given prefix.
"""
if not prefix.endswith("__"):
prefix += "__"
return {
k.replace(prefix, ""): v
for k, v in vars(self).items()
if k.startswith(prefix)
}
def get_initialized_instance(self, instance_or_class: Any, kwargs: Dict) -> Any:
"""Initialize instance or class.
Parameters
----------
instance_or_class : Any
Instance or class to initialize with kwargs.
kwargs : Dict
Parameters for instance or class initialization.
Returns
-------
Any
Initialized instance.
"""
if is_pytorch_instance(instance_or_class):
if not kwargs:
return instance_or_class
return type(instance_or_class)(**kwargs)
return instance_or_class(**kwargs)
def _initialize_module(
self,
module_name: str,
default: Optional[str] = None,
**extra_kwargs,
):
"""Initialize a module.
Parameters
----------
module_name : str
Name of the module to initialize.
default : str, optional
Default value to use if module is not defined.
**extra_kwargs
Additional keyword arguments to pass to module initialization.
These are mainly for known required parameters that may be missing
from the class attributes.
Returns
-------
self
"""
module_or_name = getattr(self, module_name, default)
if isinstance(module_or_name, str):
setattr(self, module_name, get_module(module_name, module_or_name))
kwargs = self.collect_params_for(prefix=f"{module_name}__")
kwargs.update(extra_kwargs)
setattr(
self,
f"{module_name}_",
self.get_initialized_instance(getattr(self, module_name, default), kwargs),
)
return self
def _load_module_to_device(self, name: str):
"""Load initialized torch.nn.Module to device.
Parameters
----------
name : str
Name of the module to load.
Returns
-------
self
"""
if not name.endswith("_"):
name += "_"
module = getattr(self, name)
if is_pytorch_instance(module):
setattr(self, name, module.to(self.device))
return self
def initialize_model(self):
"""Initialize the model.
Returns
-------
self
"""
self._initialize_module("model")
self._load_module_to_device(name="model")
return self
def initialize_criterion(self):
"""Initialize the criterion.
Returns
-------
self
"""
self._initialize_module("criterion")
self._load_module_to_device(name="criterion")
return self
def get_all_learnable_params(self) -> List[nn.Parameter]:
"""Get all learnable parameters.
Returns
-------
List[nn.Parameter]
all learnable parameters
"""
model = self.model_
criterion = self.criterion_
if model is None or criterion is None:
raise ValueError(
"Model and criterion must be initialized before getting"
" learnable parameters.",
)
model_parameters = model.named_parameters()
criterion_parameters = criterion.named_parameters()
parameters = dict(model_parameters)
for param_name, param in criterion_parameters:
if param_name not in parameters:
parameters[param_name] = param
return [param for param in parameters.values() if param.requires_grad]
def initialize_optimizer(self):
"""Initialize the optimizer.
Returns
-------
self
"""
params = self.get_all_learnable_params()
return self._initialize_module(
module_name="optimizer",
default="SGD",
params=params,
lr=self.lr,
)
def initialize_activation(self):
"""Initialize the activation function.
Returns
-------
nn.modules.activation
The activation function
Raises
------
ValueError
Invalid activation name
"""
return self._initialize_module("activation", default="Identity")
def initialize_lr_scheduler(self) -> TorchLRScheduler:
"""Initialize the lr scheduler.
Returns
-------
torch.optim.lr_scheduler._LRScheduler
The scheduler object
Raises
------
ValueError
Invalid scheduler name
"""
return self._initialize_module(
"lr_scheduler",
default="ConstantLR",
optimizer=self.optimizer_, # type: ignore[attr-defined]
)
def initialize(self):
"""Initialize the components of the model.
Returns
-------
self
"""
set_random_seed(self.seed, self.deterministic)
self.initialize_model()
self.initialize_criterion()
self.initialize_activation()
self.initialize_optimizer()
self.initialize_lr_scheduler()
self.initialized_ = True
return self
def _set_mode(self, training: bool = True) -> None:
"""Set mode for the model.
Parameters
----------
training : bool, default=True
Whether to set the model to training mode or evaluation mode.
"""
if not self.initialized_:
self.initialize()
self.model_.train(training) # type: ignore[attr-defined]
def _forward_pass(self, batch, **fit_params):
"""Run the forward pass.
Parameters
----------
batch
Batch of data.
**fit_params : dict, optional
Additional parameters to pass to the model's `forward` method.
Returns
-------
Any
The model's output.
"""
X = to_tensor(batch, device=self.device)
if self.concatenate_features:
out = self.model_(X, **fit_params) # type: ignore[attr-defined]
else:
out = self.model_(**X, **fit_params) # type: ignore[attr-defined]
return out
def _get_loss(self, target: torch.Tensor, preds: torch.Tensor) -> torch.Tensor:
"""Apply criterion and get the loss value.
Parameters
----------
target : torch.Tensor
Target tensor.
preds : torch.Tensor
Predictions tensor.
Returns
-------
loss : torch.Tensor
Loss tensor.
"""
return self.criterion_( # type: ignore[attr-defined]
preds.squeeze(),
target.squeeze(),
)
def _train_step(self, batch, **fit_params) -> Dict[str, torch.Tensor]:
"""Train the model for one step.
Parameters
----------
batch
Batch of data.
**fit_params : dict, optional
Additional parameters to pass to the model's `forward` method.
Returns
-------
Dict[str, torch.Tensor]
A dictionary containing the loss tensor.
"""
self._set_mode(training=True)
self.optimizer_.zero_grad(set_to_none=True) # type: ignore[attr-defined]
if isinstance(batch, (tuple, list)):
X, target = batch
target = to_tensor(target, device=self.device)
else:
X = batch
target = None
preds = self._forward_pass(X, **fit_params)
if target is not None:
loss = self._get_loss(target, preds)
else:
# XXX: batch may not always be a tuple of two elements
raise NotImplementedError
loss.backward()
self.optimizer_.step() # type: ignore[attr-defined]
if self.lr_update_per_batch:
self.lr_scheduler_.step() # type: ignore[attr-defined]
return {"loss": loss}
def _validation_step(self, batch, **fit_params) -> Dict[str, torch.Tensor]:
"""Perform a validation step.
Parameters
----------
batch : tuple
The batch of data.
training : bool, default=False
Whether to set the model to training mode.
**predict_params : dict, optional
Additional parameters to pass to the model's `forward` method.
Returns
-------
Dict[str, torch.Tensor]
A dictionary containing the loss tensor and the predictions tensor.
"""
self._set_mode(training=False)
if isinstance(batch, (tuple, list)):
X, y = batch
y = to_tensor(y, device=self.device)
else:
X = batch
y = None
with torch.no_grad():
preds = self._forward_pass(X, **fit_params)
if y is not None:
loss = self._get_loss(y, preds)
else:
# XXX: `batch` may not always be a tuple
raise NotImplementedError
return {"loss": loss, "preds": preds}
def _run_one_epoch(
self,
data_loader,
step_fn: Callable,
training: bool,
feature_columns: Optional[Union[str, List[str]]] = None,
target_columns: Optional[Union[str, List[str]]] = None,
**fit_params,
):
"""Run one epoch of training or validation.
Parameters
----------
data_loader
Data loader for the data.
step_fn : Callable
Function to call for each step.
training : bool
Whether the run is for training or not.
feature_columns : Optional[Union[str, List[str]]], optional
List of feature columns in the dataset. This is required when the input is \
a Hugging Face Dataset, by default None
target_columns : Optional[Union[str, List[str]]], optional
List of target columns in the dataset. This is required when \
the input is a Hugging Face Dataset, by default None
**fit_params : dict, optional
Additional parameters to pass to the model's `forward` method.
Returns
-------
self : `PTModel`
Raises
------
AssertionError
If the loss is NaN at any point during training.
"""
batch_losses = []
# if data is a HF dataset
if feature_columns is not None:
if target_columns is not None:
for batch in data_loader:
if self.concatenate_features:
batch_features = torch.cat(
[batch[feature] for feature in feature_columns],
dim=1,
)
else:
batch_features = {k: batch[k] for k in feature_columns}
try:
batch_labels = torch.cat(
[batch[target] for target in target_columns],
dim=1,
)
except IndexError:
batch_labels = torch.cat(
[batch[target].unsqueeze(1) for target in target_columns],
dim=1,
)
batch = (batch_features, batch_labels) # noqa: PLW2901
output = step_fn(batch, **fit_params)
loss = output["loss"].item()
assert not np.isnan(loss).any(), "Loss is NaN. Aborting training."
batch_losses.append(loss)
else:
raise NotImplementedError
else:
for batch in data_loader:
output = step_fn(batch, **fit_params)
loss = output["loss"].item()
assert not np.isnan(loss).any(), "Loss is NaN. Aborting training."
batch_losses.append(loss)
if training:
self.train_loss_.add(np.mean(batch_losses))
else:
self.val_loss_.add(np.mean(batch_losses))
if training and not self.lr_update_per_batch:
self.lr_scheduler_.step() # type: ignore[attr-defined]
def _get_dataset(
self,
X: Union[Dataset, DatasetDict, TorchDataset, np.ndarray, torch.Tensor],
y: Optional[Union[np.ndarray, torch.Tensor]] = None,
) -> Union[Dataset, DatasetDict, TorchDataset]:
"""Get dataset.
Parameters
----------
X : Union[Dataset, DatasetDict, TorchDataset, np.ndarray, torch.Tensor]
The features of the data.
y : np.ndarray, optional
The labels of the data.
Returns
-------
TorchDataset
The dataset object.
"""
if isinstance(X, (Dataset, TorchDataset, DatasetDict)):
return X
if MetaTensor is not None and isinstance(X, MetaTensor):
return PTDataset(X.data, y)
if isinstance(X, (np.ndarray, torch.Tensor)):
return PTDataset(X, y)
raise ValueError(
"`X` must be a numpy array or a `torch.utils.data.Dataset` instance."
f" Got {type(X)} instead.",
)
def _get_dataloader(
self,
dataset: Union[Dataset, TorchDataset],
test: bool = False,
):
"""Get PyTorch DataLoader for the data.
Parameters
----------
dataset : TorchDataset
Data to load.
test : bool, default=False
Whether to load the data for testing or not.
Returns
-------
A dataloader for the data.
"""
assert isinstance(dataset, (TorchDataset, Dataset)), (
"`dataset` must be a `torch.utils.data.Dataset` or"
f"`datasets.Dataset` instance. Got {type(dataset)} instead."
)
if test:
kwargs = self.collect_params_for(prefix="test_loader")
data_loader = self.test_loader
else:
kwargs = self.collect_params_for(prefix="train_loader")
data_loader = self.train_loader
if "batch_size" not in kwargs:
kwargs["batch_size"] = self.batch_size
if kwargs["batch_size"] == -1:
kwargs["batch_size"] = len(dataset)
return data_loader(dataset, num_workers=self.num_workers, **kwargs)
def _train_loop(
self,
X: Union[Dataset, DatasetDict, np.ndarray, TorchDataset],
y: Optional[np.ndarray] = None,
feature_columns: Optional[Union[str, List[str]]] = None,
target_columns: Optional[Union[str, List[str]]] = None,
splits_mapping: Optional[dict] = None,
**fit_params,
):
"""Run the training loop.
Parameters
----------
X : Union[Dataset, DatasetDict, np.ndarray, TorchDataset],
The features of the data.
y : np.ndarray, optional
The labels of the data.
feature_columns : Optional[Union[str, List[str]]], optional
List of feature columns in the dataset. This is required when the input is \
a Hugging Face Dataset, by default None
target_columns : Optional[Union[str, List[str]]], optional
List of target columns in the dataset. This is required when \
the input is a Hugging Face Dataset, by default None
splits_mapping: Optional[dict], optional
Mapping from 'train', 'validation' and 'test' to dataset splits names, \
used when input is a dataset dictionary, by default None
**fit_params : dict, optional
Additional parameters to pass to the model's `forward` method.
Returns
-------
self : `PTModel`
"""
dataset = self._get_dataset(X, y)
do_validation = isinstance(dataset, DatasetDict)
if do_validation:
train_dataset = dataset[splits_mapping["train"]]
val_dataset = dataset[splits_mapping["validation"]]
else:
train_dataset = dataset
# get the data loaders
train_loader = self._get_dataloader(train_dataset)
if do_validation:
val_loader = self._get_dataloader(val_dataset, test=True)
save_dir = self.save_dir if self.save_dir else os.getcwd()
model_dir = join(save_dir, "saved_models", self.model_name)
best_loss = np.inf
for epoch in range(1, self.max_epochs + 1):
self._run_one_epoch(
data_loader=train_loader,
step_fn=self._train_step,
training=True,
feature_columns=feature_columns,
target_columns=target_columns,
**fit_params,
)
LOGGER.info(
"[%d/%d] \
Training loss: %0.4f \t",
epoch,
self.max_epochs,
self.train_loss_.pop(),
)
if do_validation:
self._run_one_epoch(
data_loader=val_loader,
step_fn=self._validation_step,
training=False,
feature_columns=feature_columns,
target_columns=target_columns,
**fit_params,
)
val_loss = self.val_loss_.pop()
LOGGER.info(
"[%d/%d] \
Validation loss: %0.4f \t",
epoch,
self.max_epochs,
val_loss,
)
if val_loss < best_loss:
LOGGER.info("Best model saved at epoch %d in %s", epoch, model_dir)
self.save_model(filepath=model_dir, epoch=epoch, is_best=True)
if (
self.save_every < 0 or epoch % self.save_every == 0
) and not self.save_best_only:
self.save_model(filepath=model_dir, epoch=epoch)
return self
def partial_fit(
self,
X: Union[Dataset, DatasetDict, np.ndarray, TorchDataset],
y: Optional[np.ndarray] = None,
feature_columns: Optional[Union[str, List[str]]] = None,
target_columns: Optional[Union[str, List[str]]] = None,
splits_mapping: Optional[dict] = None,
**fit_params,
):
"""Fit the model to the data.
Parameters
----------
X : Union[Dataset, DatasetDict, np.ndarray, TorchDataset],
The features of the data.
y : np.ndarray, optional
The labels of the data.
feature_columns : Optional[Union[str, List[str]]], optional
List of feature columns in the dataset. This is required when the input is \
a Hugging Face Dataset, by default None
target_columns : Optional[Union[str, List[str]]], optional
List of target columns in the dataset. This is required when \
the input is a Hugging Face Dataset, by default None
splits_mapping: Optional[dict], optional
Mapping from 'train', 'validation' and 'test' to dataset splits names, \
used when input is a dataset dictionary, by default None
**fit_params : dict, optional
Additional parameters to pass to the model's `forward` method.
Returns
-------
self : `PTModel`
"""
if not self.initialized_:
self.initialize()
with contextlib.suppress(KeyboardInterrupt):
self._train_loop(
X,
y=y,
feature_columns=feature_columns,
target_columns=target_columns,
splits_mapping=splits_mapping,
**fit_params,
)
return self
def fit(
self,
X: Union[Dataset, DatasetDict, np.ndarray, TorchDataset],
y: Optional[np.ndarray] = None,
feature_columns: Optional[Union[str, List[str]]] = None,
target_columns: Optional[Union[str, List[str]]] = None,
transforms: Optional[Callable] = None,
splits_mapping: dict = None,
**fit_params,
):
"""Fit the model.
Parameters
----------
X : Union[Dataset, np.ndarray, TorchDataset]
The data features or a Hugging Face Dataset containing features and labels.
y : Optional[ArrayLike], optional
The labels of the data. This is required when the input data is not \
a Hugging Face Dataset and only contains features, by default None
feature_columns : Optional[Union[str, List[str]]], optional
List of feature columns in the dataset. This is required when the input is \
a Hugging Face Dataset, by default None
target_columns : Optional[Union[str, List[str]]], optional
List of target columns in the dataset. This is required when the input is \
a Hugging Face Dataset, by default None
transforms : Optional[Callable], optional
Transform function to be applied when __getitem__ is called \
when the input is a Hugging Face Dataset, by default None
splits_mapping: Optional[dict], optional
Mapping from 'train', 'validation' and 'test' to dataset splits names, \
used when input is a dataset dictionary,
by default {"train": "train", "validation": "validation"}
Returns
-------
self : `PTModel`
Raises
------
ValueError
If `X` is a Hugging Face Dataset and the feature column(s) is not provided.
"""
if splits_mapping is None:
splits_mapping = {"train": "train", "validation": "validation"}
if not self.warm_start or not self.initialized_:
self.initialize()
if isinstance(X, (Dataset, DatasetDict)):
if feature_columns is None:
raise ValueError(
"Missing feature columns 'feature_columns'. Please provide \
the name of feature columns when using a \
Hugging Face dataset as the input.",
)
if isinstance(feature_columns, str):
feature_columns = [feature_columns]
if target_columns is None:
LOGGER.warning(
"Missing target columns 'target_columns'. Please provide \
the name of target columns when using a \
Hugging Face dataset for supervised training.",
)
if isinstance(target_columns, str):
target_columns = [target_columns]
if isinstance(X, DatasetDict):
train_split = get_split(X, "train", splits_mapping)
try:
val_split = get_split(X, "validation", splits_mapping)
except ValueError:
LOGGER.info("No validation split was found.")
val_split = None
if val_split is None:
return self.fit(
X[train_split],
feature_columns=feature_columns,
target_columns=target_columns,
transforms=transforms,
)
splits_mapping["train"] = train_split
splits_mapping["validation"] = val_split
format_kwargs = {} if transforms is None else {"transform": transforms}
with X[train_split].formatted_as(
"custom" if transforms is not None else "torch",
columns=feature_columns + target_columns,
**format_kwargs,
), X[val_split].formatted_as(
"custom" if transforms is not None else "torch",
columns=feature_columns + target_columns,
**format_kwargs,
):
self.partial_fit(
X,
feature_columns=feature_columns,
target_columns=target_columns,
splits_mapping=splits_mapping,
**fit_params,
)
else:
format_kwargs = {} if transforms is None else {"transform": transforms}
with X.formatted_as(
"custom" if transforms is not None else "torch",
columns=feature_columns + target_columns,
**format_kwargs,
):
self.partial_fit(
X,
feature_columns=feature_columns,
target_columns=target_columns,
**fit_params,
)
else: