使用增强数据训练
翻转
切割
颜色
[总结]
1.读取图像
%matplotlib inline
import torch
import torchvision
from torch import nn
from d2l import torch as d2l
d2l.set_figsize()
img = d2l.Image.open('../img/test.png')
d2l.plt.imshow(img);
def apply(img, aug, num_rows=2, num_cols=4, scale=1.5):
Y = [aug(img) for _ in range(num_rows * num_cols)]
d2l.show_images(Y, num_rows, num_cols, scale=scale)
水平翻转
apply(img, torchvision.transforms.RandomHorizontalFlip())
# 在水平方向进行随机翻转
上下翻转图像
# 上下翻转图像
apply(img, torchvision.transforms.RandomVerticalFlip())
随机裁剪
shape_aug = torchvision.transforms.RandomResizedCrop(
(200, 200), scale=(0.1, 1), ratio=(0.5, 2))
apply(img, shape_aug)
随机更改图片亮度
apply(img, torchvision.transforms.ColorJitter(
brightness=0.5, contrast=0, saturation=0, hue=0))
随机更改图片的色调,亮度(brightness)对比度(contrast)饱和度(saturation)色调(hue)
# 随机更改图片的色调,亮度(brightness)对比度(contrast)饱和度(saturation)色调(hue)
color_aug = torchvision.transforms.ColorJitter(
brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5)
apply(img, color_aug)
结合多种图像增广方法
augs = torchvision.transforms.Compose([
torchvision.transforms.RandomHorizontalFlip(),
color_aug, shape_aug])
apply(img, augs)
all_images = torchvision.datasets.CIFAR10(
train=True, root="../data", download=True)
d2l.show_images([
all_images[i][0] for i in range(32)], 4, 8, scale=0.8);
# 只使用最简单的随机左右翻转
train_augs = torchvision.transforms.Compose([
torchvision.transforms.RandomHorizontalFlip(),
torchvision.transforms.ToTensor()])
test_augs = torchvision.transforms.Compose([
torchvision.transforms.ToTensor()])
# 定义一个辅助函数,以便于读取图像和应用图像增广
def load_cifar10(is_train, augs, batch_size):
dataset = torchvision.datasets.CIFAR10(
root="../data", train=is_train,
transform=augs, download=True)
dataloader = torch.utils.data.DataLoader(
dataset, batch_size=batch_size, shuffle=is_train,
num_workers=0)
return dataloader
标注一个数据集很贵
网络架构
微调
微调中的权重初始化