scvi.dataloaders.SemiSupervisedDataSplitter#

class scvi.dataloaders.SemiSupervisedDataSplitter(adata_manager, unlabeled_category, train_size=0.9, validation_size=None, n_samples_per_label=None, use_gpu=False, **kwargs)[source]#

Creates data loaders train_set, validation_set, test_set.

If train_size + validation_set < 1 then test_set is non-empty. The ratio between labeled and unlabeled data in adata will be preserved in the train/test/val sets.

Parameters
adata_manager : AnnDataManager

AnnDataManager object that has been created via setup_anndata.

unlabeled_category

Category to treat as unlabeled

train_size : float (default: 0.9)

float, or None (default is 0.9)

validation_size : float | NoneOptional[float] (default: None)

float, or None (default is None)

n_samples_per_label : int | NoneOptional[int] (default: None)

Number of subsamples for each label class to sample per epoch

use_gpu : bool (default: False)

Use default GPU if available (if None or True), or index of GPU to use (if int), or name of GPU (if str, e.g., ‘cuda:0’), or use CPU (if False).

**kwargs

Keyword args for data loader. If adata has labeled data, data loader class is SemiSupervisedDataLoader, else data loader class is AnnDataLoader.

Examples

>>> adata = scvi.data.synthetic_iid()
>>> scvi.model.SCVI.setup_anndata(adata, labels_key="labels")
>>> adata_manager = scvi.model.SCVI(adata).adata_manager
>>> unknown_label = 'label_0'
>>> splitter = SemiSupervisedDataSplitter(adata, unknown_label)
>>> splitter.setup()
>>> train_dl = splitter.train_dataloader()

Attributes table#

dims

A tuple describing the shape of your data.

has_prepared_data

Return bool letting you know if datamodule.prepare_data() has been called or not.

has_setup_fit

Return bool letting you know if datamodule.setup(stage='fit') has been called or not.

has_setup_predict

Return bool letting you know if datamodule.setup(stage='predict') has been called or not.

has_setup_test

Return bool letting you know if datamodule.setup(stage='test') has been called or not.

has_setup_validate

Return bool letting you know if datamodule.setup(stage='validate') has been called or not.

has_teardown_fit

Return bool letting you know if datamodule.teardown(stage='fit') has been called or not.

has_teardown_predict

Return bool letting you know if datamodule.teardown(stage='predict') has been called or not.

has_teardown_test

Return bool letting you know if datamodule.teardown(stage='test') has been called or not.

has_teardown_validate

Return bool letting you know if datamodule.teardown(stage='validate') has been called or not.

hparams

The collection of hyperparameters saved with save_hyperparameters().

hparams_initial

The collection of hyperparameters saved with save_hyperparameters().

name

test_transforms

Optional transforms (or collection of transforms) you can apply to test dataset.

train_transforms

Optional transforms (or collection of transforms) you can apply to train dataset.

val_transforms

Optional transforms (or collection of transforms) you can apply to validation dataset.

Methods table#

add_argparse_args(parent_parser, **kwargs)

Extends existing argparse by default LightningDataModule attributes.

from_argparse_args(args, **kwargs)

Create an instance from CLI arguments.

from_datasets([train_dataset, val_dataset, ...])

Create an instance from torch.utils.data.Dataset.

get_init_arguments_and_types()

Scans the DataModule signature and returns argument names, types and default values.

on_after_batch_transfer(batch, dataloader_idx)

Override to alter or apply batch augmentations to your batch after it is transferred to the device.

on_before_batch_transfer(batch, dataloader_idx)

Override to alter or apply batch augmentations to your batch before it is transferred to the device.

on_load_checkpoint(checkpoint)

Called by Lightning to restore your model.

on_predict_dataloader()

Called before requesting the predict dataloader.

on_save_checkpoint(checkpoint)

Called by Lightning when saving a checkpoint to give you a chance to store anything else you might want to save.

on_test_dataloader()

Called before requesting the test dataloader.

on_train_dataloader()

Called before requesting the train dataloader.

on_val_dataloader()

Called before requesting the val dataloader.

predict_dataloader()

Implement one or multiple PyTorch DataLoaders for prediction.

prepare_data()

Use this to download and prepare data.

save_hyperparameters(*args[, ignore, frame, ...])

Save arguments to hparams attribute.

setup([stage])

Split indices in train/test/val sets.

size([dim])

Return the dimension of each input either as a tuple or list of tuples.

teardown([stage])

Called at the end of fit (train + validate), validate, test, predict, or tune.

test_dataloader()

Implement one or multiple PyTorch DataLoaders for testing.

train_dataloader()

Implement one or more PyTorch DataLoaders for training.

transfer_batch_to_device(batch, device, ...)

Override this hook if your DataLoader returns tensors wrapped in a custom data structure.

val_dataloader()

Implement one or multiple PyTorch DataLoaders for validation.

Attributes#

dims#

SemiSupervisedDataSplitter.dims#

A tuple describing the shape of your data. Extra functionality exposed in size.

Deprecated since version v1.5: Will be removed in v1.7.0.

has_prepared_data#

SemiSupervisedDataSplitter.has_prepared_data#

Return bool letting you know if datamodule.prepare_data() has been called or not.

Returns

True if datamodule.prepare_data() has been called. False by default.

Return type

bool

Deprecated since version v1.4: Will be removed in v1.6.0.

has_setup_fit#

SemiSupervisedDataSplitter.has_setup_fit#

Return bool letting you know if datamodule.setup(stage='fit') has been called or not.

Returns

True if datamodule.setup(stage='fit') has been called. False by default.

Return type

bool

Deprecated since version v1.4: Will be removed in v1.6.0.

has_setup_predict#

SemiSupervisedDataSplitter.has_setup_predict#

Return bool letting you know if datamodule.setup(stage='predict') has been called or not.

Returns

True if datamodule.setup(stage='predict') has been called. False by default.

Return type

bool

Deprecated since version v1.4: Will be removed in v1.6.0.

has_setup_test#

SemiSupervisedDataSplitter.has_setup_test#

Return bool letting you know if datamodule.setup(stage='test') has been called or not.

Returns

True if datamodule.setup(stage='test') has been called. False by default.

Return type

bool

Deprecated since version v1.4: Will be removed in v1.6.0.

has_setup_validate#

SemiSupervisedDataSplitter.has_setup_validate#

Return bool letting you know if datamodule.setup(stage='validate') has been called or not.

Returns

True if datamodule.setup(stage='validate') has been called. False by default.

Return type

bool

Deprecated since version v1.4: Will be removed in v1.6.0.

has_teardown_fit#

SemiSupervisedDataSplitter.has_teardown_fit#

Return bool letting you know if datamodule.teardown(stage='fit') has been called or not.

Returns

True if datamodule.teardown(stage='fit') has been called. False by default.

Return type

bool

Deprecated since version v1.4: Will be removed in v1.6.0.

has_teardown_predict#

SemiSupervisedDataSplitter.has_teardown_predict#

Return bool letting you know if datamodule.teardown(stage='predict') has been called or not.

Returns

True if datamodule.teardown(stage='predict') has been called. False by default.

Return type

bool

Deprecated since version v1.4: Will be removed in v1.6.0.

has_teardown_test#

SemiSupervisedDataSplitter.has_teardown_test#

Return bool letting you know if datamodule.teardown(stage='test') has been called or not.

Returns

True if datamodule.teardown(stage='test') has been called. False by default.

Return type

bool

Deprecated since version v1.4: Will be removed in v1.6.0.

has_teardown_validate#

SemiSupervisedDataSplitter.has_teardown_validate#

Return bool letting you know if datamodule.teardown(stage='validate') has been called or not.

Returns

True if datamodule.teardown(stage='validate') has been called. False by default.

Return type

bool

Deprecated since version v1.4: Will be removed in v1.6.0.

hparams#

SemiSupervisedDataSplitter.hparams#

The collection of hyperparameters saved with save_hyperparameters(). It is mutable by the user. For the frozen set of initial hyperparameters, use hparams_initial.

Returns

mutable hyperparameters dicionary

Return type

Union[AttributeDict, dict, Namespace]

hparams_initial#

SemiSupervisedDataSplitter.hparams_initial#

The collection of hyperparameters saved with save_hyperparameters(). These contents are read-only. Manual updates to the saved hyperparameters can instead be performed through hparams.

Returns

immutable initial hyperparameters

Return type

AttributeDict

name#

SemiSupervisedDataSplitter.name: str = Ellipsis#

test_transforms#

SemiSupervisedDataSplitter.test_transforms#

Optional transforms (or collection of transforms) you can apply to test dataset.

Deprecated since version v1.5: Will be removed in v1.7.0.

train_transforms#

SemiSupervisedDataSplitter.train_transforms#

Optional transforms (or collection of transforms) you can apply to train dataset.

Deprecated since version v1.5: Will be removed in v1.7.0.

val_transforms#

SemiSupervisedDataSplitter.val_transforms#

Optional transforms (or collection of transforms) you can apply to validation dataset.

Deprecated since version v1.5: Will be removed in v1.7.0.

Methods#

add_argparse_args#

classmethod SemiSupervisedDataSplitter.add_argparse_args(parent_parser, **kwargs)#

Extends existing argparse by default LightningDataModule attributes.

Return type

ArgumentParser

from_argparse_args#

classmethod SemiSupervisedDataSplitter.from_argparse_args(args, **kwargs)#

Create an instance from CLI arguments.

Parameters
args : Namespace | ArgumentParserUnion[Namespace, ArgumentParser]

The parser or namespace to take arguments from. Only known arguments will be parsed and passed to the LightningDataModule.

**kwargs

Additional keyword arguments that may override ones in the parser or namespace. These must be valid DataModule arguments.

Example:

parser = ArgumentParser(add_help=False)
parser = LightningDataModule.add_argparse_args(parser)
module = LightningDataModule.from_argparse_args(args)

from_datasets#

classmethod SemiSupervisedDataSplitter.from_datasets(train_dataset=None, val_dataset=None, test_dataset=None, batch_size=1, num_workers=0)#

Create an instance from torch.utils.data.Dataset.

Parameters
train_dataset : Dataset | Sequence[Dataset] | Mapping | NoneUnion[Dataset, Sequence[Dataset], Mapping[str, Dataset], None] (default: None)

(optional) Dataset to be used for train_dataloader()

val_dataset : Dataset | Sequence[Dataset] | NoneUnion[Dataset, Sequence[Dataset], None] (default: None)

(optional) Dataset or list of Dataset to be used for val_dataloader()

test_dataset : Dataset | Sequence[Dataset] | NoneUnion[Dataset, Sequence[Dataset], None] (default: None)

(optional) Dataset or list of Dataset to be used for test_dataloader()

batch_size : int (default: 1)

Batch size to use for each dataloader. Default is 1.

num_workers : int (default: 0)

Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process. Number of CPUs available.

get_init_arguments_and_types#

classmethod SemiSupervisedDataSplitter.get_init_arguments_and_types()#

Scans the DataModule signature and returns argument names, types and default values.

Returns

(argument name, set with argument types, argument default value).

Return type

List with tuples of 3 values

on_after_batch_transfer#

SemiSupervisedDataSplitter.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/predicting so that you can add different logic as per your requirement.

Note

This hook only runs on single GPU training and DDP (no data-parallel). Data-Parallel support will come in near future.

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
Raises

MisconfigurationException – If using data-parallel, Trainer(strategy='dp').

on_before_batch_transfer#

SemiSupervisedDataSplitter.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/predicting so that you can add different logic as per your requirement.

Note

This hook only runs on single GPU training and DDP (no data-parallel). Data-Parallel support will come in near future.

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
Raises

MisconfigurationException – If using data-parallel, Trainer(strategy='dp').

on_load_checkpoint#

SemiSupervisedDataSplitter.on_load_checkpoint(checkpoint)#

Called by Lightning to restore your model. If you saved something with on_save_checkpoint() this is your chance to restore this.

Parameters
checkpoint : {str: Any}Dict[str, Any]

Loaded checkpoint

Example:

def on_load_checkpoint(self, checkpoint):
    # 99% of the time you don't need to implement this method
    self.something_cool_i_want_to_save = checkpoint['something_cool_i_want_to_save']

Note

Lightning auto-restores global step, epoch, and train state including amp scaling. There is no need for you to restore anything regarding training.

Return type

None

on_predict_dataloader#

SemiSupervisedDataSplitter.on_predict_dataloader()#

Called before requesting the predict dataloader.

Deprecated since version v1.5: on_predict_dataloader() is deprecated and will be removed in v1.7.0. Please use predict_dataloader() directly.

Return type

None

on_save_checkpoint#

SemiSupervisedDataSplitter.on_save_checkpoint(checkpoint)#

Called by Lightning when saving a checkpoint to give you a chance to store anything else you might want to save.

Parameters
checkpoint : {str: Any}Dict[str, Any]

The full checkpoint dictionary before it gets dumped to a file. Implementations of this hook can insert additional data into this dictionary.

Example:

def on_save_checkpoint(self, checkpoint):
    # 99% of use cases you don't need to implement this method
    checkpoint['something_cool_i_want_to_save'] = my_cool_pickable_object

Note

Lightning saves all aspects of training (epoch, global step, etc…) including amp scaling. There is no need for you to store anything about training.

Return type

None

on_test_dataloader#

SemiSupervisedDataSplitter.on_test_dataloader()#

Called before requesting the test dataloader.

Deprecated since version v1.5: on_test_dataloader() is deprecated and will be removed in v1.7.0. Please use test_dataloader() directly.

Return type

None

on_train_dataloader#

SemiSupervisedDataSplitter.on_train_dataloader()#

Called before requesting the train dataloader.

Deprecated since version v1.5: on_train_dataloader() is deprecated and will be removed in v1.7.0. Please use train_dataloader() directly.

Return type

None

on_val_dataloader#

SemiSupervisedDataSplitter.on_val_dataloader()#

Called before requesting the val dataloader.

Deprecated since version v1.5: on_val_dataloader() is deprecated and will be removed in v1.7.0. Please use val_dataloader() directly.

Return type

None

predict_dataloader#

SemiSupervisedDataSplitter.predict_dataloader()#

Implement one or multiple PyTorch DataLoaders for prediction.

It’s recommended that all data downloads and preparation happen in prepare_data().

Note

Lightning adds the correct sampler for distributed and arbitrary hardware There is no need to set it yourself.

Return type

DataLoader | Sequence[DataLoader]Union[DataLoader, Sequence[DataLoader]]

Returns

A torch.utils.data.DataLoader or a sequence of them specifying prediction samples.

Note

In the case where you return multiple prediction dataloaders, the predict() will have an argument dataloader_idx which matches the order here.

prepare_data#

SemiSupervisedDataSplitter.prepare_data()#

Use this to download and prepare data.

Warning

DO NOT set state to the model (use setup instead) since this is NOT called on every GPU in DDP/TPU

Example:

def prepare_data(self):
    # good
    download_data()
    tokenize()
    etc()

    # bad
    self.split = data_split
    self.some_state = some_other_state()

In DDP prepare_data can be called in two ways (using Trainer(prepare_data_per_node)):

  1. Once per node. This is the default and is only called on LOCAL_RANK=0.

  2. Once in total. Only called on GLOBAL_RANK=0.

Example:

# DEFAULT
# called once per node on LOCAL_RANK=0 of that node
Trainer(prepare_data_per_node=True)

# call on GLOBAL_RANK=0 (great for shared file systems)
Trainer(prepare_data_per_node=False)

Note

Setting prepare_data_per_node with the trainer flag is deprecated and will be removed in v1.7.0. Please set prepare_data_per_node in LightningDataModule or LightningModule directly instead.

This is called before requesting the dataloaders:

model.prepare_data()
initialize_distributed()
model.setup(stage)
model.train_dataloader()
model.val_dataloader()
model.test_dataloader()
Return type

None

save_hyperparameters#

SemiSupervisedDataSplitter.save_hyperparameters(*args, ignore=None, frame=None, logger=True)#

Save arguments to hparams attribute.

Parameters
args

single object of dict, NameSpace or OmegaConf or string names or arguments from class __init__

ignore : Sequence[str] | str | NoneUnion[Sequence[str], str, None] (default: None)

an argument name or a list of argument names from class __init__ to be ignored

frame : frame | NoneOptional[frame] (default: None)

a frame object. Default is None

logger : bool (default: True)

Whether to send the hyperparameters to the logger. Default: True

Example::
>>> 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
>>> 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
>>> 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
>>> 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
Return type

None

setup#

SemiSupervisedDataSplitter.setup(stage=None)[source]#

Split indices in train/test/val sets.

size#

SemiSupervisedDataSplitter.size(dim=None)#

Return the dimension of each input either as a tuple or list of tuples. You can index this just as you would with a torch tensor.

Deprecated since version v1.5: Will be removed in v1.7.0.

Return type

Tuple | List[Tuple]Union[Tuple, List[Tuple]]

teardown#

SemiSupervisedDataSplitter.teardown(stage=None)#

Called at the end of fit (train + validate), validate, test, predict, or tune.

Parameters
stage : str | NoneOptional[str] (default: None)

either 'fit', 'validate', 'test', or 'predict'

Return type

None

test_dataloader#

SemiSupervisedDataSplitter.test_dataloader()[source]#

Implement one or multiple PyTorch DataLoaders for testing.

The dataloader you return will not be reloaded unless you set :paramref:`~pytorch_lightning.trainer.Trainer.reload_dataloaders_every_n_epochs` to a postive integer.

For data processing use the following pattern:

However, the above are only necessary for distributed processing.

Warning

do not assign state in prepare_data

Note

Lightning adds the correct sampler for distributed and arbitrary hardware. There is no need to set it yourself.

Returns

A torch.utils.data.DataLoader or a sequence of them specifying testing samples.

Example:

def test_dataloader(self):
    transform = transforms.Compose([transforms.ToTensor(),
                                    transforms.Normalize((0.5,), (1.0,))])
    dataset = MNIST(root='/path/to/mnist/', train=False, transform=transform,
                    download=True)
    loader = torch.utils.data.DataLoader(
        dataset=dataset,
        batch_size=self.batch_size,
        shuffle=False
    )

    return loader

# can also return multiple dataloaders
def test_dataloader(self):
    return [loader_a, loader_b, ..., loader_n]

Note

If you don’t need a test dataset and a test_step(), you don’t need to implement this method.

Note

In the case where you return multiple test dataloaders, the test_step() will have an argument dataloader_idx which matches the order here.

train_dataloader#

SemiSupervisedDataSplitter.train_dataloader()[source]#

Implement one or more PyTorch DataLoaders for training.

Returns

A collection of torch.utils.data.DataLoader specifying training samples. In the case of multiple dataloaders, please see this page.

The dataloader you return will not be reloaded unless you set :paramref:`~pytorch_lightning.trainer.Trainer.reload_dataloaders_every_n_epochs` to a positive integer.

For data processing use the following pattern:

However, the above are only necessary for distributed processing.

Warning

do not assign state in prepare_data

Note

Lightning adds the correct sampler for distributed and arbitrary hardware. There is no need to set it yourself.

Example:

# single dataloader
def train_dataloader(self):
    transform = transforms.Compose([transforms.ToTensor(),
                                    transforms.Normalize((0.5,), (1.0,))])
    dataset = MNIST(root='/path/to/mnist/', train=True, transform=transform,
                    download=True)
    loader = torch.utils.data.DataLoader(
        dataset=dataset,
        batch_size=self.batch_size,
        shuffle=True
    )
    return loader

# multiple dataloaders, return as list
def train_dataloader(self):
    mnist = MNIST(...)
    cifar = CIFAR(...)
    mnist_loader = torch.utils.data.DataLoader(
        dataset=mnist, batch_size=self.batch_size, shuffle=True
    )
    cifar_loader = torch.utils.data.DataLoader(
        dataset=cifar, batch_size=self.batch_size, shuffle=True
    )
    # each batch will be a list of tensors: [batch_mnist, batch_cifar]
    return [mnist_loader, cifar_loader]

# multiple dataloader, return as dict
def train_dataloader(self):
    mnist = MNIST(...)
    cifar = CIFAR(...)
    mnist_loader = torch.utils.data.DataLoader(
        dataset=mnist, batch_size=self.batch_size, shuffle=True
    )
    cifar_loader = torch.utils.data.DataLoader(
        dataset=cifar, batch_size=self.batch_size, shuffle=True
    )
    # each batch will be a dict of tensors: {'mnist': batch_mnist, 'cifar': batch_cifar}
    return {'mnist': mnist_loader, 'cifar': cifar_loader}

transfer_batch_to_device#

SemiSupervisedDataSplitter.transfer_batch_to_device(batch, device, dataloader_idx)#

Override this hook if your DataLoader returns tensors wrapped in a custom data structure.

The data types listed below (and any arbitrary nesting of them) are supported out of the box:

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/predicting so that you can add different logic as per your requirement.

Note

This hook only runs on single GPU training and DDP (no data-parallel). Data-Parallel support will come in near future.

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(data, device)
    return batch
Raises

MisconfigurationException – If using data-parallel, Trainer(strategy='dp').

See also

  • move_data_to_device()

  • apply_to_collection()

val_dataloader#

SemiSupervisedDataSplitter.val_dataloader()[source]#

Implement one or multiple PyTorch DataLoaders for validation.

The dataloader you return will not be reloaded unless you set :paramref:`~pytorch_lightning.trainer.Trainer.reload_dataloaders_every_n_epochs` to a positive integer.

It’s recommended that all data downloads and preparation happen in prepare_data().

Note

Lightning adds the correct sampler for distributed and arbitrary hardware There is no need to set it yourself.

Returns

A torch.utils.data.DataLoader or a sequence of them specifying validation samples.

Examples:

def val_dataloader(self):
    transform = transforms.Compose([transforms.ToTensor(),
                                    transforms.Normalize((0.5,), (1.0,))])
    dataset = MNIST(root='/path/to/mnist/', train=False,
                    transform=transform, download=True)
    loader = torch.utils.data.DataLoader(
        dataset=dataset,
        batch_size=self.batch_size,
        shuffle=False
    )

    return loader

# can also return multiple dataloaders
def val_dataloader(self):
    return [loader_a, loader_b, ..., loader_n]

Note

If you don’t need a validation dataset and a validation_step(), you don’t need to implement this method.

Note

In the case where you return multiple validation dataloaders, the validation_step() will have an argument dataloader_idx which matches the order here.