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
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 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 |
|
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
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 |
|
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 1081 1082 |
|
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
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 1521 1522 1523 1524 1525 1526 |
|
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
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 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 |
|
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
2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 |
|
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
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 |
|
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
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 1186 1187 |
|
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
|