deeptab.data
- class deeptab.data.TabularDataset(cat_features_list, num_features_list, embeddings_list=None, labels=None, return_batch_object=False)[source]
Custom dataset for handling structured tabular data with separate categorical and numerical features.
This dataset is task-agnostic and simply stores and retrieves features and labels without any task-specific preprocessing. Label dtype conversion should be handled externally by the DataModule or training logic.
- Parameters:
cat_features_list (list of Tensors) – A list of tensors representing the categorical features.
num_features_list (list of Tensors) – A list of tensors representing the numerical features.
embeddings_list (list of Tensors, optional) – A list of tensors representing the embeddings.
labels (Tensor, optional) – A tensor of labels. If None, the dataset is used for prediction.
return_batch_object (bool, default=False) – If True, returns a TabularBatch object instead of a tuple. For backward compatibility, defaults to False.
- class deeptab.data.TabularDataModule(preprocessor, batch_size, shuffle, regression, X_val=None, y_val=None, val_size=0.2, random_state=101, stratify=True, sampler=None, **dataloader_kwargs)[source]
A PyTorch Lightning data module for managing training and validation data loaders in a structured way.
This class simplifies the process of batch-wise data loading for training and validation datasets during the training loop, and is particularly useful when working with PyTorch Lightning’s training framework.
- Parameters:
preprocessor – object An instance of your preprocessor class.
batch_size – int Size of batches for the DataLoader.
shuffle – bool Whether to shuffle the training data in the DataLoader.
X_val – DataFrame or None, optional Validation features. If None, uses train-test split.
y_val – array-like or None, optional Validation labels. If None, uses train-test split.
val_size – float, optional Proportion of data to include in the validation split if
X_valandy_valare None.random_state – int, optional Random seed for reproducibility in data splitting.
regression – bool, optional Whether the problem is regression (True) or classification (False).
stratify – bool, optional Whether to stratify the validation split on the labels for classification tasks. Ignored for regression. Defaults to True.
- classmethod from_datasets(train_dataset=None, val_dataset=None, test_dataset=None, predict_dataset=None, batch_size=1, num_workers=0, **datamodule_kwargs)
Create an instance from torch.utils.data.Dataset.
- Parameters:
train_dataset (
Union[Dataset,Iterable[Dataset],None]) – Optional dataset or iterable of datasets to be used for train_dataloader()val_dataset (
Union[Dataset,Iterable[Dataset],None]) – Optional dataset or iterable of datasets to be used for val_dataloader()test_dataset (
Union[Dataset,Iterable[Dataset],None]) – Optional dataset or iterable of datasets to be used for test_dataloader()predict_dataset (
Union[Dataset,Iterable[Dataset],None]) – Optional dataset or iterable of datasets to be used for predict_dataloader()batch_size (
int) – Batch size to use for each dataloader. Default is 1. This parameter gets forwarded to the__init__if the datamodule has such a name defined in its signature.num_workers (
int) – Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process. Number of CPUs available. This parameter gets forwarded to the__init__if the datamodule has such a name defined in its signature.**datamodule_kwargs (
Any) – Additional parameters that get passed down to the datamodule’s__init__.
- Return type:
LightningDataModule
- property hparams: AttributeDict | MutableMapping
The collection of hyperparameters saved with
save_hyperparameters(). It is mutable by the user. For the frozen set of initial hyperparameters, usehparams_initial.- Returns:
Mutable hyperparameters dictionary
- property hparams_initial: AttributeDict
The collection of hyperparameters saved with
save_hyperparameters(). These contents are read-only. Manual updates to the saved hyperparameters can instead be performed throughhparams.- Returns:
immutable initial hyperparameters
- Return type:
AttributeDict
- load_from_checkpoint(cls, checkpoint_path, map_location=None, hparams_file=None, weights_only=None, **kwargs)
Primary way of loading a datamodule from a checkpoint. When Lightning saves a checkpoint it stores the arguments passed to
__init__in the checkpoint under"datamodule_hyper_parameters".Any arguments specified through **kwargs will override args stored in
"datamodule_hyper_parameters".- Parameters:
checkpoint_path (
Union[str,Path,IO]) – Path to checkpoint. This can also be a URL, or file-like objectmap_location (
Union[device,str,int,Callable[[UntypedStorage,str],Optional[UntypedStorage]],dict[Union[device,str,int],Union[device,str,int]],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 intorch.load().hparams_file (
Union[str,Path,None]) –Optional path to a
.yamlor.csvfile with hierarchical structure as in this example:dataloader: batch_size: 32You most likely won’t need this since Lightning will always save the hyperparameters to the checkpoint. However, if your checkpoint weights don’t have the hyperparameters saved, use this method to pass in a
.yamlfile with the hparams you’d like to use. These will be converted into adictand passed into yourLightningDataModulefor use.If your datamodule’s
hparamsargument isNamespaceand.yamlfile has hierarchical structure, you need to refactor your datamodule to treathparamsasdict.weights_only (
Optional[bool]) – IfTrue, restricts loading tostate_dictsof plaintorch.Tensorand other primitive types. If loading a checkpoint from a trusted source that contains annn.Module, useweights_only=False. If loading checkpoint from an untrusted source, we recommend usingweights_only=True. For more information, please refer to the PyTorch Developer Notes on Serialization Semantics.**kwargs (
Any) – Any extra keyword args needed to init the datamodule. Can also be used to override saved hyperparameter values.
- Return type:
Self- Returns:
LightningDataModuleinstance with loaded weights and hyperparameters (if available).
Note
load_from_checkpointis a class method. You must use yourLightningDataModuleclass to call it instead of theLightningDataModuleinstance, or aTypeErrorwill be raised.Example:
# load weights without mapping ... datamodule = MyLightningDataModule.load_from_checkpoint('path/to/checkpoint.ckpt') # or load weights and hyperparameters from separate files. datamodule = MyLightningDataModule.load_from_checkpoint( 'path/to/checkpoint.ckpt', hparams_file='/path/to/hparams_file.yaml' ) # override some of the params with new values datamodule = MyLightningDataModule.load_from_checkpoint( PATH, batch_size=32, num_workers=10, )
- load_state_dict(state_dict)
Called when loading a checkpoint, implement to reload datamodule state given datamodule state_dict.
- Parameters:
state_dict (
dict[str,Any]) – the datamodule state returned bystate_dict.- Return type:
None
- on_after_batch_transfer(batch, dataloader_idx)
Override to alter or apply batch augmentations to your batch after it is transferred to the device.
Note
To check the current state of execution of this hook you can use
self.trainer.training/testing/validating/predictingso that you can add different logic as per your requirement.- Parameters:
batch (
Any) – A batch of data that needs to be altered or augmented.dataloader_idx (
int) – The index of the dataloader to which the batch belongs.
- Return type:
Any- Returns:
A batch of data
Example:
def on_after_batch_transfer(self, batch, dataloader_idx): batch['x'] = gpu_transforms(batch['x']) return batch
- on_before_batch_transfer(batch, dataloader_idx)
Override to alter or apply batch augmentations to your batch before it is transferred to the device.
Note
To check the current state of execution of this hook you can use
self.trainer.training/testing/validating/predictingso that you can add different logic as per your requirement.- Parameters:
batch (
Any) – A batch of data that needs to be altered or augmented.dataloader_idx (
int) – The index of the dataloader to which the batch belongs.
- Return type:
Any- Returns:
A batch of data
Example:
def on_before_batch_transfer(self, batch, dataloader_idx): batch['x'] = transforms(batch['x']) return batch
- on_exception(exception)
Called when the trainer execution is interrupted by an exception.
- Return type:
None
- preprocess_data(X_train, y_train, X_val=None, y_val=None, embeddings_train=None, embeddings_val=None, val_size=0.2, random_state=101)[source]
Preprocesses the training and validation data.
- Parameters:
X_train (DataFrame or array-like, shape (n_samples_train, n_features)) – Training feature set.
y_train (array-like, shape (n_samples_train,)) – Training target values.
embeddings_train (array-like or list of array-like, optional) – Training embeddings if available.
X_val (DataFrame or array-like, shape (n_samples_val, n_features), optional) – Validation feature set. If None, a validation set will be created from
X_train.y_val (array-like, shape (n_samples_val,), optional) – Validation target values. If None, a validation set will be created from
y_train.embeddings_val (array-like or list of array-like, optional) – Validation embeddings if available.
val_size (float, optional) – Proportion of data to include in the validation split if
X_valandy_valare None.random_state (int, optional) – Random seed for reproducibility in data splitting.
- Return type:
None
- remove_ignored_hparams(ignore_list)
Remove ignored hyperparameters from the stored state.
This allows derived classes to drop hyperparameters previously saved by base classes.
- Parameters:
ignore_list (
list[str]) – Names of hyperparameters to remove.- Return type:
None
- save_hyperparameters(*args, ignore=None, frame=None, logger=True)
Save arguments to
hparamsattribute.- Parameters:
args (
Any) – single object ofdict,NameSpaceorOmegaConfor string names or arguments from class__init__ignore (
Union[Sequence[str],str,None]) – an argument name or a list of argument names from class__init__to be ignoredframe (
Optional[FrameType]) – a frame object. Default is Nonelogger (
bool) – Whether to send the hyperparameters to the logger. Default: True
- Return type:
None
- Example::
>>> from lightning.pytorch.core.mixins import HyperparametersMixin >>> class ManuallyArgsModel(HyperparametersMixin): ... def __init__(self, arg1, arg2, arg3): ... super().__init__() ... # manually assign arguments ... self.save_hyperparameters('arg1', 'arg3') ... def forward(self, *args, **kwargs): ... ... >>> model = ManuallyArgsModel(1, 'abc', 3.14) >>> model.hparams "arg1": 1 "arg3": 3.14>>> from lightning.pytorch.core.mixins import HyperparametersMixin >>> class AutomaticArgsModel(HyperparametersMixin): ... def __init__(self, arg1, arg2, arg3): ... super().__init__() ... # equivalent automatic ... self.save_hyperparameters() ... def forward(self, *args, **kwargs): ... ... >>> model = AutomaticArgsModel(1, 'abc', 3.14) >>> model.hparams "arg1": 1 "arg2": abc "arg3": 3.14>>> from lightning.pytorch.core.mixins import HyperparametersMixin >>> class SingleArgModel(HyperparametersMixin): ... def __init__(self, params): ... super().__init__() ... # manually assign single argument ... self.save_hyperparameters(params) ... def forward(self, *args, **kwargs): ... ... >>> model = SingleArgModel(Namespace(p1=1, p2='abc', p3=3.14)) >>> model.hparams "p1": 1 "p2": abc "p3": 3.14>>> from lightning.pytorch.core.mixins import HyperparametersMixin >>> class ManuallyArgsModel(HyperparametersMixin): ... def __init__(self, arg1, arg2, arg3): ... super().__init__() ... # pass argument(s) to ignore as a string or in a list ... self.save_hyperparameters(ignore='arg2') ... def forward(self, *args, **kwargs): ... ... >>> model = ManuallyArgsModel(1, 'abc', 3.14) >>> model.hparams "arg1": 1 "arg3": 3.14
- property schema: FeatureSchema | None
Get the feature schema after preprocessing.
- Returns:
Feature schema with metadata about categorical, numerical, and embedding features, or None if preprocessing hasn’t been done yet.
- Return type:
FeatureSchema or None
- setup(stage)[source]
Transform the data and create DataLoaders.
- state_dict()
Called when saving a checkpoint, implement to generate and save datamodule state.
- Return type:
dict[str,Any]- Returns:
A dictionary containing datamodule state.
- teardown(stage)
Called at the end of fit (train + validate), validate, test, or predict.
- Parameters:
stage (
str) – either'fit','validate','test', or'predict'- Return type:
None
- test_dataloader()[source]
Returns the test dataloader.
- Returns:
DataLoader instance for the test dataset.
- Return type:
DataLoader
- train_dataloader()[source]
Returns the training dataloader.
- Returns:
DataLoader instance for the training dataset.
- Return type:
DataLoader
- transfer_batch_to_device(batch, device, dataloader_idx)
Override this hook if your
DataLoaderreturns tensors wrapped in a custom data structure.The data types listed below (and any arbitrary nesting of them) are supported out of the box:
torch.Tensoror anything that implements.to(...)listdicttuple
For anything else, you need to define how the data is moved to the target device (CPU, GPU, TPU, …).
Note
This hook should only transfer the data and not modify it, nor should it move the data to any other device than the one passed in as argument (unless you know what you are doing). To check the current state of execution of this hook you can use
self.trainer.training/testing/validating/predictingso that you can add different logic as per your requirement.- Parameters:
batch (
Any) – A batch of data that needs to be transferred to a new device.device (
device) – The target device as defined in PyTorch.dataloader_idx (
int) – The index of the dataloader to which the batch belongs.
- Return type:
Any- Returns:
A reference to the data on the new device.
Example:
def transfer_batch_to_device(self, batch, device, dataloader_idx): if isinstance(batch, CustomBatch): # move all tensors in your custom data structure to the device batch.samples = batch.samples.to(device) batch.targets = batch.targets.to(device) elif dataloader_idx == 0: # skip device transfer for the first dataloader or anything you wish pass else: batch = super().transfer_batch_to_device(batch, device, dataloader_idx) return batchSee also
move_data_to_device()apply_to_collection()
- val_dataloader()[source]
Returns the validation dataloader.
- Returns:
DataLoader instance for the validation dataset.
- Return type:
DataLoader
- class deeptab.data.FeatureSchema(numerical_features, categorical_features, embedding_features=None)[source]
Schema describing the structure of tabular input features.
Tracks categorical, numerical, and embedding features with their preprocessing metadata and dimensions.
- Parameters:
numerical_features (
dict[str,FeatureInfo]) – Dictionary mapping numerical feature names to their metadata.categorical_features (
dict[str,FeatureInfo]) – Dictionary mapping categorical feature names to their metadata.embedding_features (
dict[str,FeatureInfo] |None) – Dictionary mapping embedding feature names to their metadata.
- classmethod from_dict(data)[source]
Create a FeatureSchema object from serialized metadata.
- Return type:
- classmethod from_preprocessor_info(num_feature_info, cat_feature_info, embedding_feature_info=None)[source]
Create a FeatureSchema from preprocessor feature info dictionaries.
- Parameters:
num_feature_info (
dict|None) – Numerical feature information from preprocessor.cat_feature_info (
dict|None) – Categorical feature information from preprocessor.embedding_feature_info (
dict|None) – Embedding feature information from preprocessor.
- Returns:
Constructed feature schema.
- Return type:
- to_dict()[source]
Return a serializable representation of the feature schema.
- Return type:
dict[str,Any]
- class deeptab.data.FeatureInfo(name, preprocessing, dimension, categories=None)[source]
Information about a single feature in the tabular dataset.
- Parameters:
name (
str) – Feature name or identifier.preprocessing (
str) – Preprocessing strategy applied to this feature.dimension (
int) – Output dimension after preprocessing (e.g., embedding size).categories (
list[Any] |None) – List of categories for categorical features, None for numerical.
- classmethod from_dict(data)[source]
Create a FeatureInfo object from serialized metadata.
- Return type:
- to_dict()[source]
Return a serializable representation of the feature metadata.
- Return type:
dict[str,Any]
- class deeptab.data.TabularBatch(numerical_features, categorical_features, embeddings=None, labels=None)[source]
Typed container for a batch of tabular data.
Provides a structured interface for accessing different feature types and labels in a batch, replacing raw tuples.
- Parameters:
numerical_features (
list[Tensor]) – List of tensors for numerical features.categorical_features (
list[Tensor]) – List of tensors for categorical features.embeddings (
list[Tensor] |None) – List of tensors for precomputed embeddings, if any.labels (
Tensor|None) – Labels for supervised learning, None for prediction mode.
- classmethod from_tuple(batch_tuple)[source]
Create a TabularBatch from the legacy tuple format.
- Parameters:
batch_tuple (
tuple) – Either ((num_feats, cat_feats, embeddings), labels) or (num_feats, cat_feats, embeddings).- Returns:
Typed batch container.
- Return type:
- to(device)[source]
Move all tensors in the batch to the specified device.
- Parameters:
device (
device|str) – Target device (e.g., ‘cuda’, ‘cpu’, ‘mps’).- Returns:
A new batch with all tensors moved to the device.
- Return type:
- to_tuple()[source]
Convert back to legacy tuple format for backward compatibility.
- Returns:
Either ((num_feats, cat_feats, embeddings), labels) or (num_feats, cat_feats, embeddings).
- Return type:
tuple