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

PyTorch torchvision computer vision module

PyTorch torchvision computer vision module

torchvision is an extension library in the PyTorch ecosystem dedicated to computer vision tasks. It provides the following core features:

  1. Pretrained models: includes implementations of classic CNN architectures (such as ResNet, VGG, AlexNet, and others)
  2. Dataset utilities: built-in common vision datasets (such as CIFAR10, MNIST, ImageNet, and others)
  3. Image transforms: provides a variety of image preprocessing and data augmentation methods
  4. Utility functions: includes auxiliary features such as video processing and image operations


# Install torchvision (usually installed with PyTorch)

pip install torch torchvision


Core components explained

1. torchvision.models

Provides pretrained computer vision models that can be used directly for transfer learning:

Example

import

torchvision.

models

as

models

Load a pre-trained model

resnet18

=

models.

resnet18

(

pretrained

=

True

)

alexnet

=

models.

alexnet

(

pretrained

=

True

)

vgg16

=

models.

vgg16

(

pretrained

=

True

)

List of commonly used models:

Model name Applicable scenarios Number of parameters Top-1 accuracy
ResNet General image classification 11M-60M 69%-80%
VGG Feature extraction 138M 71.3%
MobileNet Mobile applications 3.4M 70.6%
EfficientNet Efficient models 5M-66M 77%-84%

2. torchvision.datasets

Built-in common computer vision datasets simplify the data loading workflow:

Example

from

torchvision

import

datasets

Load the CIFAR10 dataset

train_data

=

datasets.

CIFAR10

(

    root

=

'data'

,

    train

=

True

,

    download

=

True

,

    transform

=

transforms.

ToTensor

(

)

)

Load the MNIST dataset

test_data

=

datasets.

MNIST

(

    root

=

'data'

,

    train

=

False

,

    download

=

True

)

Supported dataset types:

Example

graph TD

    A[torchvision.datasets] --> B[Classification datasets]

    A --> C[Detection datasets]

    A --> D[Segmentation datasets]

    B --> B1[CIFAR10/100]

    B --> B2[MNIST/FashionMNIST]

    B --> B3[ImageNet]

    C --> C1[COCO]

    C --> C2[VOC]

    D --> D1[Cityscapes]


3. torchvision.transforms

Core tools for image preprocessing and data augmentation:

Example

from

torchvision

import

transforms

Define an image transform pipeline

transform

=

transforms.

Compose

(

[

    transforms.

Resize

(

256

)

,

         

resize

    transforms.

CenterCrop

(

224

)

,

     

Center crop

    transforms.

ToTensor

(

)

,

         

Convert to tensor

    transforms.

Normalize

(

           

Standardization

        mean

=

[

0.485

,

0.456

,

0.406

]

,

        std

=

[

0.229

,

0.224

,

0.225

]

   

)

]

)

Categories of commonly used transforms:

Category Method Example Purpose
Geometric transformation RandomRotation, RandomResizedCrop Increase position invariance
Color transforms ColorJitter, Grayscale Improve color robustness
Blur/noise GaussianBlur, RandomErasing Prevent overfitting
Combined transforms RandomApply, RandomChoice Flexible composition strategies

Practical example: image classification workflow

1. Data Preparation

Example

import

torch

from

torchvision

import

datasets

,

transforms

from

torch.

utils

.

data

import

DataLoader

Define data transforms

train_transform

=

transforms.

Compose

(

[

    transforms.

RandomHorizontalFlip

(

)

,

    transforms.

RandomRotation

(

10

)

,

    transforms.

ToTensor

(

)

,

    transforms.

Normalize

(

(

0.5

,

)

,

(

0.5

,

)

)

]

)

Load the dataset

train_set

=

datasets.

CIFAR10

(

    root

=

'./data'

,

    train

=

True

,

    download

=

True

,

    transform

=

train_transform

)

Create a data loader

train_loader

=

DataLoader

(

    train_set

,

    batch_size

=

32

,

    shuffle

=

True

)

2. Model training

Example

import

torch.

nn

as

nn

import

torch.

optim

as

optim

Use a pretrained model

model

=

models.

resnet18

(

pretrained

=

True

)

Replace the final layer (to fit the 10 classes of CIFAR10)

num_ftrs

=

model.

fc

.

in_features

model.

fc

=

nn.

Linear

(

num_ftrs

,

10

)

Define the loss function and optimizer

criterion

=

nn.

CrossEntropyLoss

(

)

optimizer

=

optim.

SGD

(

model.

parameters

(

)

,

lr

=

0.001

,

momentum

=

0.9

)

Training loop

for

epoch

in

range

(

10

)

:

   

for

images

,

labels

in

train_loader:

        outputs

=

model

(

images

)

        loss

=

criterion

(

outputs

,

labels

)

       

        optimizer.

zero_grad

(

)

        loss.

backward

(

)

        optimizer.

step

(

)


Advanced features

1. Custom dataset

Example

from

torchvision.

datasets

import

VisionDataset

class

CustomDataset

(

VisionDataset

)

:

   

def

init

(

self

,

root

,

transform

=

None

)

:

       

super

(

)

.

init

(

root

,

transform

=

transform

)

       

Create a class that implements getitem and len

       

   

def

getitem

(

self

,

index

)

:

       

Return an (image, target) tuple

       

pass

       

   

def

len

(

self

)

:

       

Return the dataset size

       

pass

2. Model export and deployment

Example

Export to ONNX format

dummy_input

=

torch.

randn

(

1

,

3

,

224

,

224

)

torch.

onnx

.

export

(

    model

,

    dummy_input

,

   

"model.onnx"

,

    input_names

=

[

"input"

]

,

    output_names

=

[

"output"

]

)


Best Practice Recommendations

1. Data augmentation strategies:

2. Transfer learning tips:

Example

Freeze all parameters except those in the final layer

for

param

in

model.

parameters

(

)

:

    param.

requires_grad

=

False

model.

fc

.

requires_grad

=

True

3. Performance optimization:

4. Common mistakes: