Preloaded Audio Datasets
Preloaded datasets are excellent for research and experimentation. In this section, we use TorchAudio’s built-in DR_VCTK (Device Recorded VCTK) dataset. The snippet below downloads the test subset of the dataset into a folder named “audio”. Note that the dataset is sizable (approximately 1.6 GB) and may take a minute or two to download../audio folder to explore the dataset.
Preloaded Image Datasets
Next, we explore preloaded image datasets using TorchVision. In this example, we use the FashionMNIST classification dataset. A transformation is applied to convert images to tensors for further processing.Visualizing the FashionMNIST Dataset
Visualizing a subset of the dataset helps to better understand the data. The following code randomly displays a grid of 9 images along with their labels:
Working with DataLoaders
A DataLoader handles the batching and shuffling of your dataset during training. Below is an example that demonstrates how to create a DataLoader for the FashionMNIST dataset with a batch size of 64, ensuring that the data is shuffled during training.Creating a Custom Dataset
If you have your own image collection and corresponding labels, you can define a custom dataset using PyTorch’s Dataset class. In this example, we assume that image file paths and labels are stored in a CSV file namedlabels.csv.
Ensure your CSV file is formatted correctly, as shown in the example below.
Defining the Custom Dataset
Import the necessary modules and create a custom dataset class as follows:labels.csv is structured as follows:
Visualizing the Custom Dataset
The following code snippet visualizes 9 random images from your custom dataset:Custom Dataset DataLoader
Similar to preloaded datasets, you can create a DataLoader for your custom dataset. Even if the dataset contains fewer images than the specified batch size (64 in this example), the DataLoader will return all available samples.Using TorchVision’s ImageFolder
An efficient alternative for organizing images is to use TorchVision’s ImageFolder. When your images are arranged such that each class has its own subdirectory, ImageFolder automatically assigns labels based on these subdirectory names.
Conclusion
In this guide, we demonstrated techniques for working with preloaded datasets and DataLoaders in PyTorch, as well as methods for creating and visualizing custom datasets. These approaches help streamline data loading and preprocessing for model training, whether you’re using built-in libraries or your own data collections. Happy coding and exploring with PyTorch!For more details on PyTorch data handling, visit the PyTorch Documentation.