Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch Data Processing and Loading

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

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:

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

)

:

       

print

(

f

'Batch {batch_idx + 1}:'

)

       

print

(

f

'Inputs: {inputs}'

)

       

print

(

f

'Labels: {labels}'

)

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

)

print

(

image_tensor.

shape

)

 

Print the shape of the tensor

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:

   

print

(

inputs.

shape

)

 

Shape of the input data for each batch

   

print

(

labels.

shape

)

 

Shape of the labels for each batch


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

)