Training multimodal Deep Learning Models¶
Here is the documentation for the Trainer
class, that will do all the heavy lifting.
Trainer is also available from pytorch-widedeep
directly, for example, one could do:
from pytorch-widedeep.training import Trainer
or also:
from pytorch-widedeep import Trainer
Trainer ¶
Trainer(model, objective, custom_loss_function=None, optimizers=None, lr_schedulers=None, initializers=None, transforms=None, callbacks=None, metrics=None, verbose=1, seed=1, **kwargs)
Bases: BaseTrainer
Class to set the of attributes that will be used during the training process.
Parameters:
-
model
(WideDeep
) –An object of class
WideDeep
-
objective
(str
) –Defines the objective, loss or cost function.
Param aliases:
loss_function
,loss_fn
,loss
,cost_function
,cost_fn
,cost
.Possible values are:
-
binary
, aliases:logistic
,binary_logloss
,binary_cross_entropy
-
binary_focal_loss
-
multiclass
, aliases:multi_logloss
,cross_entropy
,categorical_cross_entropy
, -
multiclass_focal_loss
-
regression
, aliases:mse
,l2
,mean_squared_error
-
mean_absolute_error
, aliases:mae
,l1
-
mean_squared_log_error
, aliases:msle
-
root_mean_squared_error
, aliases:rmse
-
root_mean_squared_log_error
, aliases:rmsle
-
zero_inflated_lognormal
, aliases:ziln
-
quantile
-
tweedie
-
multitarget
, aliases:multi_target
NOTE: For
multitarget
a custom loss function must be passed -
-
custom_loss_function
(Optional[Module]
, default:None
) –It is possible to pass a custom loss function. See for example
pytorch_widedeep.losses.FocalLoss
for the required structure of the object or the Examples section in this documentation or in the repo. Note that ifcustom_loss_function
is notNone
,objective
must be 'binary', 'multiclass' or 'regression', consistent with the loss function -
optimizers
(Optional[Union[Optimizer, Dict[str, Union[Optimizer, List[Optimizer]]]]]
, default:None
) –- An instance of Pytorch's
Optimizer
object (e.g.torch.optim.Adam()
) or - a dictionary where there keys are the model components (i.e. 'wide', 'deeptabular', 'deeptext', 'deepimage' and/or 'deephead') and the values are the corresponding optimizers or list of optimizers if multiple models are used for the given data mode (e.g. two text columns/models for the deeptext component). If multiple optimizers are used the dictionary MUST contain an optimizer per model component.
if no optimizers are passed it will default to
Adam
for all model components - An instance of Pytorch's
-
lr_schedulers
(Optional[Union[LRScheduler, Dict[str, Union[LRScheduler, List[LRScheduler]]]]]
, default:None
) –- An instance of Pytorch's
LRScheduler
object (e.gtorch.optim.lr_scheduler.StepLR(opt, step_size=5)
) or - a dictionary where there keys are the model componenst (i.e. 'wide', 'deeptabular', 'deeptext', 'deepimage' and/or 'deephead') and the values are the corresponding learning rate schedulers or list of learning rate schedulers if multiple models are used for the given data mode (e.g. two text columns/models for the deeptext component).
- An instance of Pytorch's
-
initializers
(Optional[Union[Initializer, Dict[str, Union[Initializer, List[Initializer]]]]]
, default:None
) –- An instance of an
Initializer
object seepytorch-widedeep.initializers
or - a dictionary where there keys are the model components (i.e. 'wide', 'deeptabular', 'deeptext', 'deepimage' and/or 'deephead') and the values are the corresponding initializers or list of initializers if multiple models are used for the given data mode (e.g. two text columns/models for the deeptext component).
- An instance of an
-
transforms
(Optional[List[Transforms]]
, default:None
) –List with
torchvision.transforms
to be applied to the image component of the model (i.e.deepimage
) See torchvision transforms. -
callbacks
(Optional[List[Callback]]
, default:None
) –List with
Callback
objects. The three callbacks available inpytorch-widedeep
are:LRHistory
,ModelCheckpoint
andEarlyStopping
. TheHistory
and theLRShedulerCallback
callbacks are used by default. This can also be a custom callback as long as the object of typeCallback
. Seepytorch_widedeep.callbacks.Callback
or the examples folder in the repo. -
metrics
(Optional[Union[List[Metric], List[Metric]]]
, default:None
) –- List of objects of type
Metric
. Metrics available are:Accuracy
,Precision
,Recall
,FBetaScore
,F1Score
andR2Score
. This can also be a custom metric as long as it is an object of typeMetric
. Seepytorch_widedeep.metrics.Metric
or the examples folder in the repo - List of objects of type
torchmetrics.Metric
. This can be any metric from torchmetrics library Examples. This can also be a custom metric as long as it is an object of typeMetric
. See the instructions.
- List of objects of type
-
verbose
(int
, default:1
) –Verbosity level. If set to 0 nothing will be printed during training
-
seed
(int
, default:1
) –Random seed to be used internally for train/test split
Other Parameters:
-
**kwargs
–Other infrequently used arguments that can also be passed as kwargs are:
-
device:
str
string indicating the device. One of 'cpu' or 'gpu' -
num_workers:
int
number of workers to be used internally by the data loaders -
lambda_sparse:
float
lambda sparse parameter in case thedeeptabular
component isTabNet
-
class_weight:
List[float]
This is theweight
orpos_weight
parameter inCrossEntropyLoss
andBCEWithLogitsLoss
, depending on whether - reducelronplateau_criterion:
str
This sets the criterion that will be used by the lr scheduler to take a step: One of 'loss' or 'metric'. The ReduceLROnPlateau learning rate is a bit particular.
-
Attributes:
-
cyclic_lr
(bool
) –Attribute that indicates if any of the lr_schedulers is cyclic_lr (i.e.
CyclicLR
orOneCycleLR
). See Pytorch schedulers. -
feature_importance
(dict
) –dict where the keys are the column names and the values are the corresponding feature importances. This attribute will only exist if the
deeptabular
component is a Tabnet model.
Examples:
>>> import torch
>>> from torchvision.transforms import ToTensor
>>>
>>> # wide deep imports
>>> from pytorch_widedeep.callbacks import EarlyStopping, LRHistory
>>> from pytorch_widedeep.initializers import KaimingNormal, KaimingUniform, Normal, Uniform
>>> from pytorch_widedeep.models import TabResnet, Vision, BasicRNN, Wide, WideDeep
>>> from pytorch_widedeep import Trainer
>>>
>>> embed_input = [(u, i, j) for u, i, j in zip(["a", "b", "c"][:4], [4] * 3, [8] * 3)]
>>> column_idx = {k: v for v, k in enumerate(["a", "b", "c"])}
>>> wide = Wide(10, 1)
>>>
>>> # build the model
>>> deeptabular = TabResnet(blocks_dims=[8, 4], column_idx=column_idx, cat_embed_input=embed_input)
>>> deeptext = BasicRNN(vocab_size=10, embed_dim=4, padding_idx=0)
>>> deepimage = Vision()
>>> model = WideDeep(wide=wide, deeptabular=deeptabular, deeptext=deeptext, deepimage=deepimage)
>>>
>>> # set optimizers and schedulers
>>> wide_opt = torch.optim.Adam(model.wide.parameters())
>>> deep_opt = torch.optim.AdamW(model.deeptabular.parameters())
>>> text_opt = torch.optim.Adam(model.deeptext.parameters())
>>> img_opt = torch.optim.AdamW(model.deepimage.parameters())
>>>
>>> wide_sch = torch.optim.lr_scheduler.StepLR(wide_opt, step_size=5)
>>> deep_sch = torch.optim.lr_scheduler.StepLR(deep_opt, step_size=3)
>>> text_sch = torch.optim.lr_scheduler.StepLR(text_opt, step_size=5)
>>> img_sch = torch.optim.lr_scheduler.StepLR(img_opt, step_size=3)
>>>
>>> optimizers = {"wide": wide_opt, "deeptabular": deep_opt, "deeptext": text_opt, "deepimage": img_opt}
>>> schedulers = {"wide": wide_sch, "deeptabular": deep_sch, "deeptext": text_sch, "deepimage": img_sch}
>>>
>>> # set initializers and callbacks
>>> initializers = {"wide": Uniform, "deeptabular": Normal, "deeptext": KaimingNormal, "deepimage": KaimingUniform}
>>> transforms = [ToTensor]
>>> callbacks = [LRHistory(n_epochs=4), EarlyStopping]
>>>
>>> # set the trainer
>>> trainer = Trainer(model, objective="regression", initializers=initializers, optimizers=optimizers,
... lr_schedulers=schedulers, callbacks=callbacks, transforms=transforms)
Source code in pytorch_widedeep/training/trainer.py
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 |
|
fit ¶
fit(X_wide=None, X_tab=None, X_text=None, X_img=None, X_train=None, X_val=None, val_split=None, target=None, n_epochs=1, validation_freq=1, batch_size=32, custom_dataloader=None, feature_importance_sample_size=None, finetune=False, **kwargs)
Fit method.
The input datasets can be passed either directly via numpy arrays
(X_wide
, X_tab
, X_text
or X_img
) or alternatively, in
dictionaries (X_train
or X_val
).
Parameters:
-
X_wide
(Optional[ndarray]
, default:None
) –Input for the
wide
model component. Seepytorch_widedeep.preprocessing.WidePreprocessor
-
X_tab
(Optional[Union[ndarray, List[ndarray]]]
, default:None
) –Input for the
deeptabular
model component. Seepytorch_widedeep.preprocessing.TabPreprocessor
. If multiple tabular models are used for different columns, this should be a list of numpy arrays -
X_text
(Optional[Union[ndarray, List[ndarray]]]
, default:None
) –Input for the
deeptext
model component. Seepytorch_widedeep.preprocessing.TextPreprocessor
. If multiple text columns/models are used, this should be a list of numpy arrays -
X_img
(Optional[Union[ndarray, List[ndarray]]]
, default:None
) –Input for the
deepimage
model component. Seepytorch_widedeep.preprocessing.ImagePreprocessor
. If multiple image columns/models are used, this should be a list of numpy arrays -
X_train
(Optional[Dict[str, Union[ndarray, List[ndarray]]]]
, default:None
) –The training dataset can also be passed in a dictionary. Keys are 'X_wide', 'X_tab', 'X_text', 'X_img' and 'target'. Values are the corresponding matrices. Note that of multiple text or image columns/models are used, the corresponding values should be lists of numpy arrays
-
X_val
(Optional[Dict[str, Union[ndarray, List[ndarray]]]]
, default:None
) –The validation dataset can also be passed in a dictionary. Keys are 'X_wide', 'X_tab', 'X_text', 'X_img' and 'target'. Values are the corresponding matrices. Note that of multiple text or image columns/models are used, the corresponding values should be lists of numpy arrays
-
val_split
(Optional[float]
, default:None
) –train/val split fraction
-
target
(Optional[ndarray]
, default:None
) –target values
-
n_epochs
(int
, default:1
) –number of epochs
-
validation_freq
(int
, default:1
) –epochs validation frequency
-
batch_size
(int
, default:32
) –batch size
-
custom_dataloader
(Optional[DataLoader]
, default:None
) –object of class
torch.utils.data.DataLoader
. Available predefined dataloaders are inpytorch-widedeep.dataloaders
.IfNone
, a standard torchDataLoader
is used. -
finetune
(bool
, default:False
) –fine-tune individual model components. This functionality can also be used to 'warm-up' (and hence the alias
warmup
) individual components before the joined training starts, and hence its alias. See the Examples folder in the repo for more detailspytorch_widedeep
implements 3 fine-tune routines.- fine-tune all trainable layers at once. This routine is
inspired by the work of Howard & Sebastian Ruder 2018 in their
ULMfit paper. Using a
Slanted Triangular learing (see
Leslie N. Smith paper ) ,
the process is the following: i) the learning rate will
gradually increase for 10% of the training steps from max_lr/10
to max_lr. ii) It will then gradually decrease to max_lr/10
for the remaining 90% of the steps. The optimizer used in the
process is
Adam
.
and two gradual fine-tune routines, where only certain layers are trained at a time.
- The so called
Felbo
gradual fine-tune rourine, based on the the Felbo et al., 2017 DeepEmoji paper. - The
Howard
routine based on the work of Howard & Sebastian Ruder 2018 in their ULMfit paper.
For details on how these routines work, please see the Examples section in this documentation and the Examples folder in the repo.
Param Alias:warmup
- fine-tune all trainable layers at once. This routine is
inspired by the work of Howard & Sebastian Ruder 2018 in their
ULMfit paper. Using a
Slanted Triangular learing (see
Leslie N. Smith paper ) ,
the process is the following: i) the learning rate will
gradually increase for 10% of the training steps from max_lr/10
to max_lr. ii) It will then gradually decrease to max_lr/10
for the remaining 90% of the steps. The optimizer used in the
process is
Other Parameters:
-
**kwargs
–Other keyword arguments are:
-
DataLoader related parameters:
For example,sampler
,batch_sampler
,collate_fn
, etc. Please, see the pytorch DataLoader docs for details. -
Finetune related parameters:
see the source code atpytorch_widedeep._finetune
. Namely, these are:finetune_epochs
(int
): number of epochs use for fine tuningfinetune_max_lr
(float
): max lr during fine tuningroutine
(str
): one of 'howard' or 'felbo'deeptabular_gradual
(bool
): boolean indicating if thedeeptabular
component will be fine tuned graduallydeeptabular_layers
(Optional[Union[List[nn.Module], List[List[nn.Module]]]]
): List of pytorch modules indicating the layers of thedeeptabular
that will be fine tuneddeeptabular_max_lr
(Union[float, List[float]]
): max lr for thedeeptabular
componet during fine tuningdeeptext_gradual
(bool
): same asdeeptabular_gradual
but for thedeeptext
componentdeeptext_layers
(Optional[Union[List[nn.Module], List[List[nn.Module]]]]
): same asdeeptabular_gradual
but for thedeeptext
component. If there are multiple text columns/models, this should be a list of listsdeeptext_max_lr
(Union[float, List[float]]
): same asdeeptabular_gradual
but for thedeeptext
component If there are multiple text columns/models, this should be a list of floatsdeepimage_gradual
(bool
): same asdeeptext_layers
but for thedeepimage
componentdeepimage_layers
(Optional[Union[List[nn.Module], List[List[nn.Module]]]]
): same asdeeptext_layers
but for thedeepimage
componentdeepimage_max_lr
(Union[float, List[float]]
): same asdeeptext_layers
but for thedeepimage
component
-
Examples:
For a series of comprehensive examples on how to use the fit
method, please see the
Examples
folder in the repo
Source code in pytorch_widedeep/training/trainer.py
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 |
|
predict ¶
predict(X_wide=None, X_tab=None, X_text=None, X_img=None, X_test=None, batch_size=None)
Returns the predictions
The input datasets can be passed either directly via numpy arrays
(X_wide
, X_tab
, X_text
or X_img
) or alternatively, in
a dictionary (X_test
)
Parameters:
-
X_wide
(Optional[ndarray]
, default:None
) –Input for the
wide
model component. Seepytorch_widedeep.preprocessing.WidePreprocessor
-
X_tab
(Optional[Union[ndarray, List[ndarray]]]
, default:None
) –Input for the
deeptabular
model component. Seepytorch_widedeep.preprocessing.TabPreprocessor
-
X_text
(Optional[Union[ndarray, List[ndarray]]]
, default:None
) –Input for the
deeptext
model component. Seepytorch_widedeep.preprocessing.TextPreprocessor
-
X_img
(Optional[Union[ndarray, List[ndarray]]]
, default:None
) –Input for the
deepimage
model component. Seepytorch_widedeep.preprocessing.ImagePreprocessor
-
X_test
(Optional[Dict[str, Union[ndarray, List[ndarray]]]]
, default:None
) –The test dataset can also be passed in a dictionary. Keys are
X_wide
, 'X_tab', 'X_text', 'X_img' and 'target'. Values are the corresponding matrices. -
batch_size
(Optional[int]
, default:None
) –If a trainer is used to predict after having trained a model, the
batch_size
needs to be defined as it will not be defined as theTrainer
is instantiated
Returns:
-
np.ndarray:
–array with the predictions
Source code in pytorch_widedeep/training/trainer.py
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 |
|
predict_uncertainty ¶
predict_uncertainty(X_wide=None, X_tab=None, X_text=None, X_img=None, X_test=None, batch_size=None, uncertainty_granularity=1000)
Returns the predicted ucnertainty of the model for the test dataset
using a Monte Carlo method during which dropout layers are activated
in the evaluation/prediction phase and each sample is predicted N
times (uncertainty_granularity
times).
This is based on Dropout as a Bayesian Approximation: Representing Model Uncertainty in Deep Learning.
Parameters:
-
X_wide
(Optional[ndarray]
, default:None
) –Input for the
wide
model component. Seepytorch_widedeep.preprocessing.WidePreprocessor
-
X_tab
(Optional[Union[ndarray, List[ndarray]]]
, default:None
) –Input for the
deeptabular
model component. Seepytorch_widedeep.preprocessing.TabPreprocessor
-
X_text
(Optional[Union[ndarray, List[ndarray]]]
, default:None
) –Input for the
deeptext
model component. Seepytorch_widedeep.preprocessing.TextPreprocessor
-
X_img
(Optional[Union[ndarray, List[ndarray]]]
, default:None
) –Input for the
deepimage
model component. Seepytorch_widedeep.preprocessing.ImagePreprocessor
-
X_test
(Optional[Dict[str, Union[ndarray, List[ndarray]]]]
, default:None
) –The test dataset can also be passed in a dictionary. Keys are 'X_wide', 'X_tab', 'X_text', 'X_img' and 'target'. Values are the corresponding matrices.
-
batch_size
(Optional[int]
, default:None
) –If a trainer is used to predict after having trained a model, the
batch_size
needs to be defined as it will not be defined as theTrainer
is instantiated -
uncertainty_granularity
–number of times the model does prediction for each sample
Returns:
-
np.ndarray:
–- if
method = regression
, it will return an array with(max, min, mean, stdev)
values for each sample. - if
method = binary
it will return an array with(mean_cls_0_prob, mean_cls_1_prob, predicted_cls)
for each sample. - if
method = multiclass
it will return an array with(mean_cls_0_prob, mean_cls_1_prob, mean_cls_2_prob, ... , predicted_cls)
values for each sample.
- if
Source code in pytorch_widedeep/training/trainer.py
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 |
|
predict_proba ¶
predict_proba(X_wide=None, X_tab=None, X_text=None, X_img=None, X_test=None, batch_size=None)
Returns the predicted probabilities for the test dataset for binary and multiclass methods
The input datasets can be passed either directly via numpy arrays
(X_wide
, X_tab
, X_text
or X_img
) or alternatively, in
a dictionary (X_test
)
Parameters:
-
X_wide
(Optional[ndarray]
, default:None
) –Input for the
wide
model component. Seepytorch_widedeep.preprocessing.WidePreprocessor
-
X_tab
(Optional[Union[ndarray, List[ndarray]]]
, default:None
) –Input for the
deeptabular
model component. Seepytorch_widedeep.preprocessing.TabPreprocessor
-
X_text
(Optional[Union[ndarray, List[ndarray]]]
, default:None
) –Input for the
deeptext
model component. Seepytorch_widedeep.preprocessing.TextPreprocessor
-
X_img
(Optional[Union[ndarray, List[ndarray]]]
, default:None
) –Input for the
deepimage
model component. Seepytorch_widedeep.preprocessing.ImagePreprocessor
-
X_test
(Optional[Dict[str, Union[ndarray, List[ndarray]]]]
, default:None
) –The test dataset can also be passed in a dictionary. Keys are
X_wide
, 'X_tab', 'X_text', 'X_img' and 'target'. Values are the corresponding matrices. -
batch_size
(Optional[int]
, default:None
) –If a trainer is used to predict after having trained a model, the
batch_size
needs to be defined as it will not be defined as theTrainer
is instantiated
Returns:
-
ndarray
–array with the probabilities per class
Source code in pytorch_widedeep/training/trainer.py
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 |
|
save ¶
save(path, save_state_dict=False, save_optimizer=False, model_filename='wd_model.pt')
Saves the model, training and evaluation history, and the
feature_importance
attribute (if the deeptabular
component is a
Tabnet model) to disk
The Trainer
class is built so that it 'just' trains a model. With
that in mind, all the torch related parameters (such as optimizers,
learning rate schedulers, initializers, etc) have to be defined
externally and then passed to the Trainer
. As a result, the
Trainer
does not generate any attribute or additional data
products that need to be saved other than the model
object itself,
which can be saved as any other torch model (e.g. torch.save(model,
path)
).
The exception is Tabnet. If the deeptabular
component is a Tabnet
model, an attribute (a dict) called feature_importance
will be
created at the end of the training process. Therefore, a save
method was created that will save the feature importance dictionary
to a json file and, since we are here, the model weights, training
history and learning rate history.
Parameters:
-
path
(str
) –path to the directory where the model and the feature importance attribute will be saved.
-
save_state_dict
(bool
, default:False
) –Boolean indicating whether to save directly the model (and optimizer) or the model's (and optimizer's) state dictionary
-
save_optimizer
(bool
, default:False
) –Boolean indicating whether to save the optimizer
-
model_filename
(str
, default:'wd_model.pt'
) –filename where the model weights will be store
Source code in pytorch_widedeep/training/trainer.py
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 |
|