PyTorch Data Processing and Loading
In PyTorch, processing and loading data are key steps in the deep learning training workflow.
To handle data efficiently, PyTorch provides powerful tools such as torch.utils.data.Dataset and torch.utils.data.DataLoader to help manage datasets, batch loading, and data augmentation.
Introduction to PyTorch data processing and loading:
- Custom Dataset: By inheriting from
torch.utils.data.Datasetto load your own dataset. - DataLoader:
DataLoaderLoad data in batches, with multi-threaded loading and data shuffling. - Data preprocessing and augmentation: When using
torchvision.transformsPerform common image preprocessing and augmentation operations to improve model generalization. - Load standard datasets:
torchvision.datasetsProvides many common datasets, simplifying the data loading process. - Multiple data sources: By combining multiple
Datasetinstances to handle data from different sources.
Custom Dataset
torch.utils.data.Dataset is an abstract class that lets you create datasets from your own data sources.
We need to subclass it and implement the following two methods:
__len__(self): Return the number of samples in the dataset.__getitem__(self, idx): Return a sample by index.
Suppose we have a simple CSV file or some list data; we can create our own dataset by subclassing Dataset.
Example
import
torch
from
torch.
utils
.
data
import
Dataset
Custom dataset class
class
MyDataset
(
Dataset
)
:
def
init
(
self
,
X_data
,
Y_data
)
:
"""
Initialize the dataset; X_data and Y_data are two lists or arrays
X_data: input features
Y_data: target labels
"""
self
.
X_data
=
X_data
self
.
Y_data
=
Y_data
def
len
(
self
)
:
"""Return the size of the dataset"""
return
len
(
self
.
X_data
)
def
getitem
(
self
,
idx
)
:
"""Return the data at the specified index"""
x
=
torch.
tensor
(
self
.
X_data
[
idx
]
,
dtype
=
torch.
float32
)
Convert to Tensor
y
=
torch.
tensor
(
self
.
Y_data
[
idx
]
,
dtype
=
torch.
float32
)
return
x
,
y
Sample data
X_data
=
[
[
1
,
2
]
,
[
3
,
4
]
,
[
5
,
6
]
,
[
7
,
8
]
]
Input features
Y_data
=
[
1
,
0
,
1
,
0
]
Target labels
Create a dataset instance
dataset
=
MyDataset
(
X_data
,
Y_data
)
Load data with DataLoader
DataLoader is an important PyTorch tool for loading data from a Dataset in batches.
DataLoader lets us read data in batches and load it with multiple threads, improving training efficiency.
Example
from
torch.
utils
.
data
import
DataLoader
Create a DataLoader instance; batch_size sets the number of samples loaded each time
dataloader
=
DataLoader
(
dataset
,
batch_size
=
2
,
shuffle
=
True
)
Print the loaded data
for
epoch
in
range
(
1
)
:
for
batch_idx
,
(
inputs
,
labels
)
in
enumerate
(
dataloader
)
:
(
f
'Batch {batch_idx + 1}:'
)
(
f
'Inputs: {inputs}'
)
(
f
'Labels: {labels}'
)
batch_size: Number of samples loaded each time.shuffle: Whether to shuffle the data; usually set to True during training.drop_last: If the number of samples in the dataset is not evenly divisible bybatch_size, setting it toTruediscards the final incomplete batch.
Output:
Batch 1:
Inputs: tensor([[3., 4.], [1., 2.]])
Labels: tensor([0., 1.])
Batch 2:
Inputs: tensor([[7., 8.], [5., 6.]])
Labels: tensor([0., 1.])
On each iteration, DataLoader returns a batch of data, including input features (inputs) and target labels (labels).
Preprocessing and data augmentation
Data preprocessing and augmentation are essential for improving model performance.
PyTorch provides the torchvision.transforms module for common image preprocessing and augmentation operations such as rotation, cropping, and normalization.
Common image preprocessing operations:
Example
import
torchvision.
transforms
as
transforms
from
PIL
import
Image
Define the data preprocessing pipeline
transform
=
transforms.
Compose
(
[
transforms.
Resize
(
(
128
,
128
)
)
,
Resize the image to 128x128
transforms.
ToTensor
(
)
,
Convert the image to a tensor
transforms.
Normalize
(
mean
=
[
0.485
,
0.456
,
0.406
]
,
std
=
[
0.229
,
0.224
,
0.225
]
)
Standardization
]
)
Load the image
image
=
Image.
open
(
'image.jpg'
)
Apply preprocessing
image_tensor
=
transform
(
image
)
(
image_tensor.
shape
)
Print the shape of the tensor
transforms.Compose(): Combine multiple transforms together.transforms.Resize(): Resize the image.transforms.ToTensor(): Convert the image to a PyTorch tensor, with values normalized to the[0, 1]range.transforms.Normalize(): Normalize image data; normalization is typically needed when using a pretrained model.
Image data augmentation
Data augmentation increases data diversity by randomly transforming the training data, helping the model generalize better, for example through random flips, rotations, and crops.
Example
transform
=
transforms.
Compose
(
[
transforms.
RandomHorizontalFlip
(
)
,
Random horizontal flip
transforms.
RandomRotation
(
30
)
,
Random rotation by 30 degrees
transforms.
RandomResizedCrop
(
128
)
,
Random crop and resize to 128x128
transforms.
ToTensor
(
)
,
transforms.
Normalize
(
mean
=
[
0.485
,
0.456
,
0.406
]
,
std
=
[
0.229
,
0.224
,
0.225
]
)
]
)
These augmentation methods can be combined with transforms.Compose() so that each image receives different transforms during training.
Load an image dataset
For image datasets, torchvision.datasets provides many common datasets (such as CIFAR-10, ImageNet, and MNIST) as well as utilities for loading image data.
Load the MNIST dataset:
Example
import
torchvision.
datasets
as
datasets
import
torchvision.
transforms
as
transforms
Define the preprocessing operations
transform
=
transforms.
Compose
(
[
transforms.
ToTensor
(
)
,
transforms.
Normalize
(
(
0.5
,
)
,
(
0.5
,
)
)
Normalize the grayscale images
]
)
Download and load the MNIST dataset
train_dataset
=
datasets.
MNIST
(
root
=
'./data'
,
train
=
True
,
download
=
True
,
transform
=
transform
)
test_dataset
=
datasets.
MNIST
(
root
=
'./data'
,
train
=
False
,
download
=
True
,
transform
=
transform
)
Create a DataLoader
train_loader
=
DataLoader
(
train_dataset
,
batch_size
=
64
,
shuffle
=
True
)
test_loader
=
DataLoader
(
test_dataset
,
batch_size
=
64
,
shuffle
=
False
)
Iterate over the training data
for
inputs
,
labels
in
train_loader:
(
inputs.
shape
)
Shape of the input data for each batch
(
labels.
shape
)
Shape of the labels for each batch
datasets.MNIST()The MNIST dataset is downloaded and loaded automatically.transformThe transform parameter lets us preprocess the data.train=Trueandtrain=Falsedenote the training set and the test set, respectively.
Using multiple data sources (Multi-source Dataset)
If your dataset consists of multiple files or sources (for example, several image folders), you can subclass Dataset to load them all.
PyTorch provides classes such as ConcatDataset and ChainDataset to concatenate multiple datasets.
For example, if we have data in several image folders, we can merge them into one dataset:
Example
from
torch.
utils
.
data
import
ConcatDataset
Suppose dataset1 and dataset2 are two Dataset objects
combined_dataset
=
ConcatDataset
(
[
dataset1
,
dataset2
]
)
combined_loader
=
DataLoader
(
combined_dataset
,
batch_size
=
64
,
shuffle
=
True
)