数据增广
以图片为例,在不同的灯光,色温,以及灯光反射的影响下,对识别可能会造成很大影响。这时候我们希望样本有更多的多样性,则可以在语言里面加入各种不同的背景噪音,或者改变图片的颜色和形状
1.常见的增强方法
1.1 翻转和裁剪
左右翻转通常不会改变对象的类别(上下翻转可能会),我们可以使用transforms模块来创建RandomFlipLeftRight实例,就有50%的概率左右翻转。使用RandomFlipTopBottom实例,使图像各有50%的几率向上或向下翻转。
切割可使用RandomResizedCrop来实现:
shape_aug = torchvision.transforms.RandomResizedCrop(
(200, 200), scale=(0.1, 1), ratio=(0.5, 2))
apply(img, shape_aug)
意为随机裁剪一个面积为原始面积10%到100%的区域,该区域的宽高比从0.5~2之间随机取值,然后,区域的宽度和高度都被缩放到200像素。
1.2 改变颜色
另一种增强方法时改变颜色,有四个方面:亮度,对比度,饱和度和色调。
apply(img, torchvision.transforms.ColorJitter(
brightness=0.5, contrast=0, saturation=0, hue=0))
四个参数分别为亮度,对比度,饱和度和色调,值的含义是在原始值的对应区间波动,比如亮度取0.5,即在原始值的50%到150%之间。可同时设置。
1.3 其他方法
显然可以结合起来使用,然后也有锐化,高斯模糊,加黑块等处理方法:
http://github.com/aleju/imgaug
2.使用数据增广来训练
遇到的问题:
直接使用d2l.resnet18()会遇到问题,自己重写一遍就能正确运行了(用的A卡,device用的torch_directml)
import torch
import torchvision
from torch import nn
from d2l import torch as d2l
from torch.nn import functional as F
import torch_directml
d2l.set_figsize()
img = d2l.Image.open('../img/cat1.jpg')
d2l.plt.imshow(img)
device = torch_directml.device()
# 作用多少次,生成两行四列
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) # 裁剪
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)
# 使用CIFAR10数据集,彩色图
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()]) # 先做变换。再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)
# transform 就是在读的时候就做增广
dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size,
shuffle=is_train, num_workers=d2l.get_dataloader_workers())
return dataloader
# @save
def train_batch_ch13(net, X, y, loss, trainer, devices):
"""用多GPU进行小批量训练"""
if isinstance(X, list):
# 微调BERT中所需
X = [x.to(devices) for x in X]
else:
X = X.to(devices)
y = y.to(devices)
net.train()
trainer.zero_grad()
pred = net(X)
l = loss(pred, y)
l.sum().backward()
trainer.step()
train_loss_sum = l.sum()
train_acc_sum = d2l.accuracy(pred, y)
return train_loss_sum, train_acc_sum
# @save 多GPU的
def train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs,
device):
"""用多GPU进行模型训练"""
timer, num_batches = d2l.Timer(), len(train_iter)
animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0, 1],
legend=['train loss', 'train acc', 'test acc'])
# net = nn.DataParallel(net, device_ids=devices).to(devices[0])
for epoch in range(num_epochs):
# 4个维度:储存训练损失,训练准确度,实例数,特点数
metric = d2l.Accumulator(4)
for i, (features, labels) in enumerate(train_iter):
timer.start()
l, acc = train_batch_ch13(
net, features, labels, loss, trainer, device)
metric.add(l, acc, labels.shape[0], labels.numel())
timer.stop()
if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
animator.add(epoch + (i + 1) / num_batches,
(metric[0] / metric[2], metric[1] / metric[3],
None))
test_acc = d2l.evaluate_accuracy_gpu(net, test_iter)
animator.add(epoch + 1, (None, None, test_acc))
print(f'loss {metric[0] / metric[2]:.3f}, train acc '
f'{metric[1] / metric[3]:.3f}, test acc {test_acc:.3f}')
print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec on '
f'{str(devices)}')
def init_weights(m):
if type(m) in [nn.Linear, nn.Conv2d]:
nn.init.xavier_uniform_(m.weight)
def resnet18(num_classes, in_channels=3):
class Residual(nn.Module):
def __init__(self, input_channels, num_channels, use_1x1conv=False, strides=1):
super(Residual, self).__init__()
self.conv1 = nn.Conv2d(input_channels, num_channels, kernel_size=3, padding=1, stride=strides)
self.conv2 = nn.Conv2d(num_channels, num_channels, kernel_size=3, padding=1)
if use_1x1conv:
self.conv3 = nn.Conv2d(input_channels, num_channels, kernel_size=1, stride=strides)
else:
self.conv3 = None
self.bn1 = nn.BatchNorm2d(num_channels)
self.bn2 = nn.BatchNorm2d(num_channels)
def forward(self, X):
Y = F.relu(self.bn1(self.conv1(X)))
Y = self.bn2(self.conv2(Y))
if self.conv3:
X = self.conv3(X)
return F.relu(Y + X)
def resnet_block(input_channels, num_channels, num_residuals, first_block=False):
blk = []
for i in range(num_residuals):
if i == 0 and not first_block:
blk.append(Residual(input_channels, num_channels, use_1x1conv=True, strides=2))
else:
blk.append(Residual(num_channels, num_channels))
return blk
b1 = nn.Sequential(nn.Conv2d(in_channels, 64, kernel_size=7, stride=2, padding=3),
nn.BatchNorm2d(64), nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2, padding=1))
b2 = nn.Sequential(*resnet_block(64, 64, 2, first_block=True))
b3 = nn.Sequential(*resnet_block(64, 128, 2))
b4 = nn.Sequential(*resnet_block(128, 256, 2))
b5 = nn.Sequential(*resnet_block(256, 512, 2))
net = nn.Sequential(b1, b2, b3, b4, b5,
nn.AdaptiveAvgPool2d((1, 1)),
nn.Flatten(), nn.Linear(512, num_classes))
return net
# batch_size, devices, net = 256, d2l.try_all_gpus(), d2l.resnet18(10, 3).to(device)
batch_size, devices, net = 256, d2l.try_all_gpus(), resnet18(10, 3)
net.apply(init_weights)
net.to(device)
def init_weights(m):
if type(m) in [nn.Linear, nn.Conv2d]:
nn.init.xavier_uniform_(m.weight)
net.apply(init_weights)
def train_with_data_aug(train_augs, test_augs, net, lr=0.001):
train_iter = load_cifar10(True, train_augs, batch_size)
test_iter = load_cifar10(False, test_augs, batch_size)
loss = nn.CrossEntropyLoss(reduction="none")
trainer = torch.optim.Adam(net.parameters(), lr=lr)
train_ch13(net, train_iter, test_iter, loss, trainer, 10, device)
train_with_data_aug(train_augs, test_augs, net)
d2l.plt.show()
不知道为什么,效果不是很好,明明用的都是resnet18,难道d2l的resnet18有什么优化?