After defining all the configs, we need to put it all together and this is where TabularModel
comes in. TabularModel
is the core work horse, which orchestrates and sets everything up.
TabularModel
parses the configs and:
- initializes the model
- sets up the experiment tracking framework
- initializes and sets up the
TabularDatamodule
which handles all the data transformations and preparation of the DataLoaders - sets up the callbacks and the Pytorch Lightning Trainer
- enables you to train, save, load, and predict
Initializing Tabular Model¶
Basic Usage:¶
data_config
: DataConfig: DataConfig object or path to the yaml file.model_config
: ModelConfig: A subclass of ModelConfig or path to the yaml file. Determines which model to run from the type of config.optimizer_config
: OptimizerConfig: OptimizerConfig object or path to the yaml file.trainer_config
: TrainerConfig: TrainerConfig object or path to the yaml file.experiment_config
: ExperimentConfig: ExperimentConfig object or path to the yaml file.
Usage Example¶
tabular_model = TabularModel(
data_config=data_config,
model_config=model_config,
optimizer_config=optimizer_config,
trainer_config=trainer_config,
experiment_config=experiment_config,
)
Model Sweep¶
PyTorch Tabular also provides an easy way to check performance of different models and configurations on a given dataset. This is done through the model_sweep
function. It takes in a list of model configs or one of the presets defined in pytorch_tabular.MODEL_PRESETS
and trains them on the data. It then ranks the models based on the metric provided and returns the best model.
These are the major args:
- task
: The type of prediction task. Either 'classification' or 'regression'
- train
: The training data
- test
: The test data on which performance is evaluated
- all the config objects can be passed as either the object or the path to the yaml file.
- models
: The list of models to compare. This can be one of the presets defined in pytorch_tabular.MODEL_SWEEP_PRESETS
or a list of ModelConfig
objects.
- metrics
: the list of metrics you need to track during training. The metrics should be one of the functional metrics implemented in torchmetrics
. By default, it is accuracy if classification and mean_squared_error for regression
- metrics_prob_input
: Is a mandatory parameter for classification metrics defined in the config. This defines whether the input to the metric function is the probability or the class. Length should be same as the number of metrics. Defaults to None.
- metrics_params
: The parameters to be passed to the metrics function.
- rank_metric
: The metric to use for ranking the models. The first element of the tuple is the metric name and the second element is the direction. Defaults to ('loss', "lower_is_better").
- return_best_model
: If True, will return the best model. Defaults to True.
Usage Example¶
sweep_df, best_model = model_sweep(
task="classification", # One of "classification", "regression"
train=train,
test=test,
data_config=data_config,
optimizer_config=optimizer_config,
trainer_config=trainer_config,
model_list="lite", # One of the presets defined in pytorch_tabular.MODEL_SWEEP_PRESETS
common_model_args=dict(head="LinearHead", head_config=head_config),
metrics=['accuracy', "f1_score"], # The metrics to track during training
metrics_params=[{}, {"average": "weighted"}],
metrics_prob_input=[False, True],
rank_metric=("accuracy", "higher_is_better"), # The metric to use for ranking the models.
progress_bar=True, # If True, will show a progress bar
verbose=False # If True, will print the results of each model
)
For more examples, check out the tutorial notebook - Model Sweep for example usage.
Advanced Usage¶
config
: DictConfig: Another way of initializingTabularModel
is with anDictconfig
fromomegaconf
. Although not recommended, you can create a normal dictionary with all the parameters dumped into it and create aDictConfig
fromomegaconf
and pass it here. The downside is that you'll be skipping all the validation(both type validation and logical validations). This is primarily used internally to load a saved model from a checkpoint.model_callable
: Optional[Callable]: Usually, the model callable and parameters are inferred from the ModelConfig. But in special cases, like when working with a custom model, you can pass the class(not the initialized object) to this parameter and override the config based initialization.
Training API (Supervised Learning)¶
There are two APIs for training or 'fit'-ing a model.
- High-level API
- Low-level API
The low-level API is more flexible and allows you to customize the training loop. The high-level API is easier to use and is recommended for most use cases.
High-Level API¶
pytorch_tabular.TabularModel.fit(train, validation=None, loss=None, metrics=None, metrics_prob_inputs=None, optimizer=None, optimizer_params=None, train_sampler=None, target_transform=None, max_epochs=None, min_epochs=None, seed=42, callbacks=None, datamodule=None, cache_data='memory', handle_oom=True)
¶
The fit method which takes in the data and triggers the training.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
train |
DataFrame
|
Training Dataframe |
required |
validation |
Optional[DataFrame]
|
If provided, will use this dataframe as the validation while training. Used in Early Stopping and Logging. If left empty, will use 20% of Train data as validation. Defaults to None. |
None
|
loss |
Optional[Module]
|
Custom Loss functions which are not in standard pytorch library |
None
|
metrics |
Optional[List[Callable]]
|
Custom metric functions(Callable) which has the signature metric_fn(y_hat, y) and works on torch tensor inputs. y_hat is expected to be of shape (batch_size, num_classes) for classification and (batch_size, 1) for regression and y is expected to be of shape (batch_size, 1) |
None
|
metrics_prob_inputs |
Optional[List[bool]]
|
This is a mandatory parameter for classification metrics. If the metric function requires probabilities as inputs, set this to True. The length of the list should be equal to the number of metrics. Defaults to None. |
None
|
optimizer |
Optional[Optimizer]
|
Custom optimizers which are a drop in replacements for standard PyTorch optimizers. This should be the Class and not the initialized object |
None
|
optimizer_params |
Optional[Dict]
|
The parameters to initialize the custom optimizer. |
None
|
train_sampler |
Optional[Sampler]
|
Custom PyTorch batch samplers which will be passed to the DataLoaders. Useful for dealing with imbalanced data and other custom batching strategies |
None
|
target_transform |
Optional[Union[TransformerMixin, Tuple(Callable)]]
|
If provided, applies the transform to the target before modelling and inverse the transform during prediction. The parameter can either be a sklearn Transformer which has an inverse_transform method, or a tuple of callables (transform_func, inverse_transform_func) |
None
|
max_epochs |
Optional[int]
|
Overwrite maximum number of epochs to be run. Defaults to None. |
None
|
min_epochs |
Optional[int]
|
Overwrite minimum number of epochs to be run. Defaults to None. |
None
|
seed |
Optional[int]
|
(int): Random seed for reproducibility. Defaults to 42. |
42
|
callbacks |
Optional[List[Callback]]
|
List of callbacks to be used during training. Defaults to None. |
None
|
datamodule |
Optional[TabularDatamodule]
|
The datamodule. If provided, will ignore the rest of the parameters like train, test etc and use the datamodule. Defaults to None. |
None
|
cache_data |
str
|
Decides how to cache the data in the dataloader. If set to "memory", will cache in memory. If set to a valid path, will cache in that path. Defaults to "memory". |
'memory'
|
handle_oom |
bool
|
If True, will try to handle OOM errors elegantly. Defaults to True. |
True
|
Returns:
Type | Description |
---|---|
Trainer
|
pl.Trainer: The PyTorch Lightning Trainer instance |
Source code in src/pytorch_tabular/tabular_model.py
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 |
|
pytorch_tabular.TabularModel.cross_validate(cv, train, metric=None, return_oof=False, groups=None, verbose=True, reset_datamodule=True, handle_oom=True, **kwargs)
¶
Cross validate the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cv |
Optional[Union[int, Iterable, BaseCrossValidator]]
|
Determines the cross-validation splitting strategy. Possible inputs for cv are:
|
required |
train |
DataFrame
|
The training data with labels |
required |
metric |
Optional[Union[str, Callable]]
|
The metrics to be used for evaluation.
If None, will use the first metric in the config. If str is provided, will use that
metric from the defined ones. If callable is provided, will use that function as the
metric. We expect callable to be of the form |
None
|
return_oof |
bool
|
If True, will return the out-of-fold predictions along with the cross validation results. Defaults to False. |
False
|
groups |
Optional[Union[str, ndarray]]
|
Group labels for
the samples used while splitting. If provided, will be used as the
|
None
|
verbose |
bool
|
If True, will log the results. Defaults to True. |
True
|
reset_datamodule |
bool
|
If True, will reset the datamodule for each iteration. It will be slower because we will be fitting the transformations for each fold. If False, we take an approximation that once the transformations are fit on the first fold, they will be valid for all the other folds. Defaults to True. |
True
|
handle_oom |
bool
|
If True, will handle out of memory errors elegantly |
True
|
**kwargs |
Additional keyword arguments to be passed to the |
{}
|
Returns:
Name | Type | Description |
---|---|---|
DataFrame |
The dataframe with the cross validation results |
Source code in src/pytorch_tabular/tabular_model.py
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 |
|
Low-Level API¶
The low-level API is more flexible and allows you to write more complicated logic like cross validation, ensembling, etc. The low-level API is more verbose and requires you to write more code, but it comes with more control to the user.
The fit
method is split into three sub-methods:
-
prepare_dataloader
-
prepare_model
-
train
prepare_dataloader¶
This method is responsible for setting up the TabularDataModule
and returns the object. You can save this object using save_dataloader
and load it later using load_datamodule
to skip the data preparation step. This is useful when you are doing cross validation or ensembling.
pytorch_tabular.TabularModel.prepare_dataloader(train, validation=None, train_sampler=None, target_transform=None, seed=42, cache_data='memory')
¶
Prepares the dataloaders for training and validation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
train |
DataFrame
|
Training Dataframe |
required |
validation |
Optional[DataFrame]
|
If provided, will use this dataframe as the validation while training. Used in Early Stopping and Logging. If left empty, will use 20% of Train data as validation. Defaults to None. |
None
|
train_sampler |
Optional[Sampler]
|
Custom PyTorch batch samplers which will be passed to the DataLoaders. Useful for dealing with imbalanced data and other custom batching strategies |
None
|
target_transform |
Optional[Union[TransformerMixin, Tuple(Callable)]]
|
If provided, applies the transform to the target before modelling and inverse the transform during prediction. The parameter can either be a sklearn Transformer which has an inverse_transform method, or a tuple of callables (transform_func, inverse_transform_func) |
None
|
seed |
Optional[int]
|
Random seed for reproducibility. Defaults to 42. |
42
|
cache_data |
str
|
Decides how to cache the data in the dataloader. If set to "memory", will cache in memory. If set to a valid path, will cache in that path. Defaults to "memory". |
'memory'
|
Returns: TabularDatamodule: The prepared datamodule
Source code in src/pytorch_tabular/tabular_model.py
prepare_model¶
This method is responsible for setting up and initializing the model and takes in the prepared datamodule as an input. It returns the model instance.
pytorch_tabular.TabularModel.prepare_model(datamodule, loss=None, metrics=None, metrics_prob_inputs=None, optimizer=None, optimizer_params=None)
¶
Prepares the model for training.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
datamodule |
TabularDatamodule
|
The datamodule |
required |
loss |
Optional[Module]
|
Custom Loss functions which are not in standard pytorch library |
None
|
metrics |
Optional[List[Callable]]
|
Custom metric functions(Callable) which has the signature metric_fn(y_hat, y) and works on torch tensor inputs |
None
|
metrics_prob_inputs |
Optional[List[bool]]
|
This is a mandatory parameter for classification metrics. If the metric function requires probabilities as inputs, set this to True. The length of the list should be equal to the number of metrics. Defaults to None. |
None
|
optimizer |
Optional[Optimizer]
|
Custom optimizers which are a drop in replacements for standard PyTorch optimizers. This should be the Class and not the initialized object |
None
|
optimizer_params |
Optional[Dict]
|
The parameters to initialize the custom optimizer. |
None
|
Returns:
Name | Type | Description |
---|---|---|
BaseModel |
BaseModel
|
The prepared model |
Source code in src/pytorch_tabular/tabular_model.py
train¶
This method is responsible for training the model and takes in the prepared datamodule and model as an input. It returns the trained model instance.
pytorch_tabular.TabularModel.train(model, datamodule, callbacks=None, max_epochs=None, min_epochs=None, handle_oom=True)
¶
Trains the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model |
LightningModule
|
The PyTorch Lightning model to be trained. |
required |
datamodule |
TabularDatamodule
|
The datamodule |
required |
callbacks |
Optional[List[Callback]]
|
List of callbacks to be used during training. Defaults to None. |
None
|
max_epochs |
Optional[int]
|
Overwrite maximum number of epochs to be run. Defaults to None. |
None
|
min_epochs |
Optional[int]
|
Overwrite minimum number of epochs to be run. Defaults to None. |
None
|
handle_oom |
bool
|
If True, will try to handle OOM errors elegantly. Defaults to True. |
True
|
Returns:
Type | Description |
---|---|
Trainer
|
pl.Trainer: The PyTorch Lightning Trainer instance |
Source code in src/pytorch_tabular/tabular_model.py
Training API (Self-Supervised Learning)¶
For self-supervised learning, there is a different API because the process is different.
- pytorch_tabular.TabularModel.pretrain: This method is responsible for pretraining the model. It takes in the the input dataframes, and other parameters to pre-train on the provided data.
- pytorch_tabular.TabularModel.create_finetune_model: If we want to use the pretrained model for finetuning, we need to create a new model with the pretrained weights. This method is responsible for creating a finetune model. It takes in the pre-trained model and returns a finetune model. The returned object is a separate instance of
TabularModel
and can be used to finetune the model. - pytorch_tabular.TabularModel.finetune: This method is responsible for finetuning the model and can only be used with a model which is created through
create_finetune_model
. It takes in the the input dataframes, and other parameters to finetune on the provided data.
Note
The dataframes passed to pretrain
need not have the target column. But even if you defined the target column in DataConfig
, it will be ignored. But the dataframes passed to finetune
must have the target column.
pytorch_tabular.TabularModel.pretrain(train, validation=None, optimizer=None, optimizer_params=None, max_epochs=None, min_epochs=None, seed=42, callbacks=None, datamodule=None, cache_data='memory')
¶
The pretrained method which takes in the data and triggers the training.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
train |
DataFrame
|
Training Dataframe |
required |
validation |
Optional[DataFrame]
|
If provided, will use this dataframe as the validation while training. Used in Early Stopping and Logging. If left empty, will use 20% of Train data as validation. Defaults to None. |
None
|
optimizer |
Optional[Optimizer]
|
Custom optimizers which are a drop in replacements for standard PyTorch optimizers. This should be the Class and not the initialized object |
None
|
optimizer_params |
Optional[Dict]
|
The parameters to initialize the custom optimizer. |
None
|
max_epochs |
Optional[int]
|
Overwrite maximum number of epochs to be run. Defaults to None. |
None
|
min_epochs |
Optional[int]
|
Overwrite minimum number of epochs to be run. Defaults to None. |
None
|
seed |
Optional[int]
|
(int): Random seed for reproducibility. Defaults to 42. |
42
|
callbacks |
Optional[List[Callback]]
|
List of callbacks to be used during training. Defaults to None. |
None
|
datamodule |
Optional[TabularDatamodule]
|
The datamodule. If provided, will ignore the rest of the parameters like train, test etc. and use the datamodule. Defaults to None. |
None
|
cache_data |
str
|
Decides how to cache the data in the dataloader. If set to "memory", will cache in memory. If set to a valid path, will cache in that path. Defaults to "memory". |
'memory'
|
Returns: pl.Trainer: The PyTorch Lightning Trainer instance
Source code in src/pytorch_tabular/tabular_model.py
pytorch_tabular.TabularModel.create_finetune_model(task, head, head_config, train, validation=None, train_sampler=None, target_transform=None, target=None, optimizer_config=None, trainer_config=None, experiment_config=None, loss=None, metrics=None, metrics_prob_input=None, metrics_params=None, optimizer=None, optimizer_params=None, learning_rate=None, target_range=None, seed=42)
¶
Creates a new TabularModel model using the pretrained weights and the new task and head.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task |
str
|
The task to be performed. One of "regression", "classification" |
required |
head |
str
|
The head to be used for the model. Should be one of the heads defined
in |
required |
head_config |
Dict
|
The config as a dict which defines the head. If left empty, will be initialized as default linear head. |
required |
train |
DataFrame
|
The training data with labels |
required |
validation |
Optional[DataFrame]
|
The validation data with labels. Defaults to None. |
None
|
train_sampler |
Optional[Sampler]
|
If provided, will be used as a batch sampler for training. Defaults to None. |
None
|
target_transform |
Optional[Union[TransformerMixin, Tuple]]
|
If provided, will be used to transform the target before training and inverse transform the predictions. |
None
|
target |
Optional[str]
|
The target column name if not provided in the initial pretraining stage. Defaults to None. |
None
|
optimizer_config |
Optional[OptimizerConfig]
|
If provided, will redefine the optimizer for fine-tuning stage. Defaults to None. |
None
|
trainer_config |
Optional[TrainerConfig]
|
If provided, will redefine the trainer for fine-tuning stage. Defaults to None. |
None
|
experiment_config |
Optional[ExperimentConfig]
|
If provided, will redefine the experiment for fine-tuning stage. Defaults to None. |
None
|
loss |
Optional[Module]
|
If provided, will be used as the loss function for the fine-tuning. By default, it is MSELoss for regression and CrossEntropyLoss for classification. |
None
|
metrics |
Optional[List[Callable]]
|
List of metrics (either callables or str) to be used for the
fine-tuning stage. If str, it should be one of the functional metrics implemented in
|
None
|
metrics_prob_input |
Optional[List[bool]]
|
Is a mandatory parameter for classification metrics This defines whether the input to the metric function is the probability or the class. Length should be same as the number of metrics. Defaults to None. |
None
|
metrics_params |
Optional[Dict]
|
The parameters for the metrics in the same order as metrics.
For eg. f1_score for multi-class needs a parameter |
None
|
optimizer |
Optional[Optimizer]
|
Custom optimizers which are a drop in replacements for standard PyTorch optimizers. If provided, the OptimizerConfig is ignored in favor of this. Defaults to None. |
None
|
optimizer_params |
Dict
|
The parameters for the optimizer. Defaults to {}. |
None
|
learning_rate |
Optional[float]
|
The learning rate to be used. Defaults to 1e-3. |
None
|
target_range |
Optional[Tuple[float, float]]
|
The target range for the regression task. Is ignored for classification. Defaults to None. |
None
|
seed |
Optional[int]
|
Random seed for reproducibility. Defaults to 42. |
42
|
Returns: TabularModel (TabularModel): The new TabularModel model for fine-tuning
Source code in src/pytorch_tabular/tabular_model.py
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 |
|
pytorch_tabular.TabularModel.finetune(max_epochs=None, min_epochs=None, callbacks=None, freeze_backbone=False)
¶
Finetunes the model on the provided data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
max_epochs |
Optional[int]
|
The maximum number of epochs to train for. Defaults to None. |
None
|
min_epochs |
Optional[int]
|
The minimum number of epochs to train for. Defaults to None. |
None
|
callbacks |
Optional[List[Callback]]
|
If provided, will be added to the callbacks for Trainer. Defaults to None. |
None
|
freeze_backbone |
bool
|
If True, will freeze the backbone by tirning off gradients. Defaults to False, which means the pretrained weights are also further tuned during fine-tuning. |
False
|
Returns:
Type | Description |
---|---|
Trainer
|
pl.Trainer: The trainer object |
Source code in src/pytorch_tabular/tabular_model.py
Model Evaluation¶
pytorch_tabular.TabularModel.predict(test, quantiles=[0.25, 0.5, 0.75], n_samples=100, ret_logits=False, include_input_features=False, device=None, progress_bar=None, test_time_augmentation=False, num_tta=5, alpha_tta=0.1, aggregate_tta='mean', tta_seed=42)
¶
Uses the trained model to predict on new data and return as a dataframe.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
test |
DataFrame
|
The new dataframe with the features defined during training |
required |
quantiles |
Optional[List]
|
For probabilistic models like Mixture Density Networks, this specifies
the different quantiles to be extracted apart from the |
[0.25, 0.5, 0.75]
|
n_samples |
Optional[int]
|
Number of samples to draw from the posterior to estimate the quantiles. Ignored for non-probabilistic models. Defaults to 100 |
100
|
ret_logits |
bool
|
Flag to return raw model outputs/logits except the backbone features along with the dataframe. Defaults to False |
False
|
include_input_features |
bool
|
DEPRECATED: Flag to include the input features in the returned dataframe. Defaults to True |
False
|
progress_bar |
Optional[str]
|
choose progress bar for tracking the progress. "rich" or "tqdm" will set the respective progress bars. If None, no progress bar will be shown. |
None
|
test_time_augmentation |
bool
|
If True, will use test time augmentation to generate predictions. The approach is very similar to what is described here But, we add noise to the embedded inputs to handle categorical features as well. (x_{aug} = x_{orig} + lpha * \epsilon) where (\epsilon \sim \mathcal{N}(0, 1)) Defaults to False |
False
|
num_tta |
float
|
The number of augumentations to run TTA for. Defaults to 0.0 |
5
|
alpha_tta |
float
|
The standard deviation of the gaussian noise to be added to the input features |
0.1
|
aggregate_tta |
Union[str, Callable]
|
The function to be used to aggregate the predictions from each augumentation. If str, should be one of "mean", "median", "min", or "max" for regression. For classification, the previous options are applied to the confidence scores (soft voting) and then converted to final prediction. An additional option "hard_voting" is available for classification. If callable, should be a function that takes in a list of 3D arrays (num_samples, num_cv, num_targets) and returns a 2D array of final probabilities (num_samples, num_targets). Defaults to "mean".' |
'mean'
|
tta_seed |
int
|
The random seed to be used for the noise added in TTA. Defaults to 42. |
42
|
Returns:
Name | Type | Description |
---|---|---|
DataFrame |
DataFrame
|
Returns a dataframe with predictions and features (if |
Source code in src/pytorch_tabular/tabular_model.py
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 |
|
pytorch_tabular.TabularModel.evaluate(test=None, test_loader=None, ckpt_path=None, verbose=True)
¶
Evaluates the dataframe using the loss and metrics already set in config.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
test |
Optional[DataFrame]
|
The dataframe to be evaluated. If not provided, will try to use the test provided during fit. If that was also not provided will return an empty dictionary |
None
|
test_loader |
Optional[DataLoader]
|
The dataloader to be used for evaluation. If provided, will use the dataloader instead of the test dataframe or the test data provided during fit. Defaults to None. |
None
|
ckpt_path |
Optional[Union[str, Path]]
|
The path to the checkpoint to be loaded. If not provided, will try to use the best checkpoint during training. |
None
|
verbose |
bool
|
If true, will print the results. Defaults to True. |
True
|
Returns: The final test result dictionary.
Source code in src/pytorch_tabular/tabular_model.py
pytorch_tabular.TabularModel.cross_validate(cv, train, metric=None, return_oof=False, groups=None, verbose=True, reset_datamodule=True, handle_oom=True, **kwargs)
¶
Cross validate the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cv |
Optional[Union[int, Iterable, BaseCrossValidator]]
|
Determines the cross-validation splitting strategy. Possible inputs for cv are:
|
required |
train |
DataFrame
|
The training data with labels |
required |
metric |
Optional[Union[str, Callable]]
|
The metrics to be used for evaluation.
If None, will use the first metric in the config. If str is provided, will use that
metric from the defined ones. If callable is provided, will use that function as the
metric. We expect callable to be of the form |
None
|
return_oof |
bool
|
If True, will return the out-of-fold predictions along with the cross validation results. Defaults to False. |
False
|
groups |
Optional[Union[str, ndarray]]
|
Group labels for
the samples used while splitting. If provided, will be used as the
|
None
|
verbose |
bool
|
If True, will log the results. Defaults to True. |
True
|
reset_datamodule |
bool
|
If True, will reset the datamodule for each iteration. It will be slower because we will be fitting the transformations for each fold. If False, we take an approximation that once the transformations are fit on the first fold, they will be valid for all the other folds. Defaults to True. |
True
|
handle_oom |
bool
|
If True, will handle out of memory errors elegantly |
True
|
**kwargs |
Additional keyword arguments to be passed to the |
{}
|
Returns:
Name | Type | Description |
---|---|---|
DataFrame |
The dataframe with the cross validation results |
Source code in src/pytorch_tabular/tabular_model.py
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 |
|
pytorch_tabular.TabularModel.bagging_predict(cv, train, test, groups=None, verbose=True, reset_datamodule=True, return_raw_predictions=False, aggregate='mean', weights=None, handle_oom=True, **kwargs)
¶
Bagging predict on the test data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cv |
Optional[Union[int, Iterable, BaseCrossValidator]]
|
Determines the cross-validation splitting strategy. Possible inputs for cv are:
|
required |
train |
DataFrame
|
The training data with labels |
required |
test |
DataFrame
|
The test data to be predicted |
required |
groups |
Optional[Union[str, ndarray]]
|
Group labels for
the samples used while splitting. If provided, will be used as the
|
None
|
verbose |
bool
|
If True, will log the results. Defaults to True. |
True
|
reset_datamodule |
bool
|
If True, will reset the datamodule for each iteration. It will be slower because we will be fitting the transformations for each fold. If False, we take an approximation that once the transformations are fit on the first fold, they will be valid for all the other folds. Defaults to True. |
True
|
return_raw_predictions |
bool
|
If True, will return the raw predictions from each fold. Defaults to False. |
False
|
aggregate |
Union[str, Callable]
|
The function to be used to aggregate the predictions from each fold. If str, should be one of "mean", "median", "min", or "max" for regression. For classification, the previous options are applied to the confidence scores (soft voting) and then converted to final prediction. An additional option "hard_voting" is available for classification. If callable, should be a function that takes in a list of 3D arrays (num_samples, num_cv, num_targets) and returns a 2D array of final probabilities (num_samples, num_targets). Defaults to "mean". |
'mean'
|
weights |
Optional[List[float]]
|
The weights to be used for aggregating the predictions
from each fold. If None, will use equal weights. This is only used when |
None
|
handle_oom |
bool
|
If True, will handle out of memory errors elegantly |
True
|
**kwargs |
Additional keyword arguments to be passed to the |
{}
|
Returns:
Name | Type | Description |
---|---|---|
DataFrame |
The dataframe with the bagged predictions. |
Source code in src/pytorch_tabular/tabular_model.py
2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 |
|
Artifact Saving and Loading¶
Saving the Model, Datamodule, and Configs¶
pytorch_tabular.TabularModel.save_config(dir)
¶
Saves the config in the specified directory.
pytorch_tabular.TabularModel.save_datamodule(dir, inference_only=False)
¶
Saves the datamodule in the specified directory.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dir |
str
|
The path to the directory to save the datamodule |
required |
inference_only |
bool
|
If True, will only save the inference datamodule without data. This cannot be used for further training, but can be used for inference. Defaults to False. |
False
|
Source code in src/pytorch_tabular/tabular_model.py
pytorch_tabular.TabularModel.save_model(dir, inference_only=False)
¶
Saves the model and checkpoints in the specified directory.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dir |
str
|
The path to the directory to save the model |
required |
inference_only |
bool
|
If True, will only save the inference only version of the datamodule |
False
|
Source code in src/pytorch_tabular/tabular_model.py
pytorch_tabular.TabularModel.save_model_for_inference(path, kind='pytorch', onnx_export_params={'opset_version': 12})
¶
Saves the model for inference.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path |
Union[str, Path]
|
path to save the model |
required |
kind |
str
|
"pytorch" or "onnx" (Experimental) |
'pytorch'
|
onnx_export_params |
Dict
|
parameters for onnx export to be passed to torch.onnx.export |
{'opset_version': 12}
|
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the model was saved successfully |
Source code in src/pytorch_tabular/tabular_model.py
pytorch_tabular.TabularModel.save_weights(path)
¶
Saves the model weights in the specified directory.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path |
str
|
The path to the file to save the model |
required |
Source code in src/pytorch_tabular/tabular_model.py
Loading the Model and Datamodule¶
pytorch_tabular.TabularModel.load_best_model()
¶
Loads the best model after training is done.
Source code in src/pytorch_tabular/tabular_model.py
pytorch_tabular.TabularModel.load_model(dir, map_location=None, strict=True)
classmethod
¶
Loads a saved model from the directory.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dir |
str
|
The directory where the model wa saved, along with the checkpoints |
required |
map_location |
Union[Dict[str, str], str, device, int, Callable, None])
|
If your checkpoint saved a GPU model and you now load on CPUs or a different number of GPUs, use this to map to the new setup. The behaviour is the same as in torch.load() |
None
|
strict |
bool)
|
Whether to strictly enforce that the keys in checkpoint_path match the keys returned by this module's state dict. Default: True. |
True
|
Returns:
Name | Type | Description |
---|---|---|
TabularModel |
TabularModel
|
The saved TabularModel |
Source code in src/pytorch_tabular/tabular_model.py
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 |
|
pytorch_tabular.TabularModel.load_weights(path)
¶
Loads the model weights in the specified directory.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path |
str
|
The path to the file to load the model from |
required |
Source code in src/pytorch_tabular/tabular_model.py
Other Functions¶
pytorch_tabular.TabularModel.find_learning_rate(model, datamodule, min_lr=1e-08, max_lr=1, num_training=100, mode='exponential', early_stop_threshold=4.0, plot=True, callbacks=None)
¶
Enables the user to do a range test of good initial learning rates, to reduce the amount of guesswork in picking a good starting learning rate.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model |
LightningModule
|
The PyTorch Lightning model to be trained. |
required |
datamodule |
TabularDatamodule
|
The datamodule |
required |
min_lr |
Optional[float]
|
minimum learning rate to investigate |
1e-08
|
max_lr |
Optional[float]
|
maximum learning rate to investigate |
1
|
num_training |
Optional[int]
|
number of learning rates to test |
100
|
mode |
Optional[str]
|
search strategy, either 'linear' or 'exponential'. If set to 'linear' the learning rate will be searched by linearly increasing after each batch. If set to 'exponential', will increase learning rate exponentially. |
'exponential'
|
early_stop_threshold |
Optional[float]
|
threshold for stopping the search. If the loss at any point is larger than early_stop_threshold*best_loss then the search is stopped. To disable, set to None. |
4.0
|
plot |
bool
|
If true, will plot using matplotlib |
True
|
callbacks |
Optional[List]
|
If provided, will be added to the callbacks for Trainer. |
None
|
Returns:
Type | Description |
---|---|
Tuple[float, DataFrame]
|
The suggested learning rate and the learning rate finder results |
Source code in src/pytorch_tabular/tabular_model.py
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 |
|
pytorch_tabular.TabularModel.summary(model=None, max_depth=-1)
¶
Prints a summary of the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
max_depth |
int
|
The maximum depth to traverse the modules and displayed in the summary. Defaults to -1, which means will display all the modules. |
-1
|