在 PyTorch 中,Compose
是 torchvision.transforms 模块中的一个类,它用于将多个图像预处理操作组合在一起,以便在深度学习任务中按顺序应用这些操作。通常,它用于预处理输入数据,例如图像,以供神经网络模型使用。
以下是如何在 PyTorch 中使用 Compose
:
import torch
from torchvision import transforms
# 创建一个图像预处理管道
preprocess = transforms.Compose([
transforms.Resize((224, 224)), # 调整图像大小
transforms.ToTensor(), # 将图像转换为张量
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # 标准化
])
在上述代码中,我们使用 Compose
创建了一个名为 preprocess
的图像预处理管道,其中包含了三个处理步骤:
transforms.Resize((224, 224))
:将图像调整为 224x224 的大小。transforms.ToTensor()
:将图像转换为张量。transforms.Normalize()
:对图像进行标准化,应用均值和标准差的归一化。