# 36图片增广
import matplotlib.pyplot as plt
import torch
import torchvision
from torch import nn
from d2l import torch as d2l
d2l.set_figsize()
img = d2l.Image.open(r'D:\worksoftware\PycharmProjects\pythonProject\image\dog.png')
d2l.plt.imshow(img)
plt.show()
# 随机水平翻转
def apply(img, aug, num_rows=2, num_cols=4, scale=1.5): #aug:增广
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()) # 水平随机翻转8次
# 随机剪裁
shape_aug = torchvision.transforms.RandomResizedCrop(
(200, 200), scale=(0.1, 1), ratio=(0.5, 2))
# 输出200x200, 范围0.1-1, 高宽比0.5-2
apply(img, shape_aug)
# 随机更改图片的亮度
apply(img, torchvision.transforms.ColorJitter(
brightness=0.5, contrast=0, saturation=0, hue=0))
# 图片增加或减少亮度0.5, 对比度, 饱和度, 色调
#随机更改图像的色调
apply(img, torchvision.transforms.ColorJitter(
brightness=0, contrast=0, saturation=0, hue=0.5))
#随机更该
color_aug = torchvision.transforms.ColorJitter(
brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5)
apply(img, color_aug)
# 结合多种图像增广方法 Compose
augs = torchvision.transforms.Compose([
torchvision.transforms.RandomResizedCrop(),
color_aug,
shape_aug
])
# 使用图像增广来进行计算
all_images = torchvision.datasets.CIFAR10(root='D:\\worksoftware\\PycharmProjects\\pythonProject\\dataset_1',train=True,download=True)
text_set = torchvision.datasets.CIFAR10(root='D:\\worksoftware\\PycharmProjects\\pythonProject\\dataset_1',train=False,download=True)
d2l.show_images([
all_images[i][0] for i in range(32)], 4, 8, scale=0.8)
plt.show() # 查看
# 只使用简单的随机左右翻转
train_augs = torchvision.transforms.Compose([
torchvision.transforms.RandomResizedCrop(),
torchvision.transforms.ToTensor()
])
test_augs = torchvision.transforms.Compose([
torchvision.transforms.ToTensor()
])
def load_cifar10(is_train,batch_size,augs):
datasets = torchvision.datasets.CIFAR10(root='D:\\worksoftware\\PycharmProjects\\pythonProject\\dataset_1',train=is_train,download=True,transform=augs)
dataloader = torch.utils.data.DataLoader(datasets,batch_size,shuffle=True,num_workers=4)
return dataloader
def train_batch_ch13(net, X, y, loss, optim, devices):
if isinstance(X, list):
X = [x.to(devices[0]) for x in X]
else:
X = X.to(devices[0])
y = y.to(devices[0])
net.train()
optim.zero_grad()
y_hat = net(X)
ls = loss(y_hat, y).sum()
ls.backward()
optim.step()
train_batch_loss = ls
train_batch_accuracy = d2l.accuracy(y_hat, y)
return train_batch_loss, train_batch_accuracy
def train_ch13(net, train_iter, test_iter, epochs, optim, loss, devices=d2l.try_all_gpus()):
timer, num_batchs = d2l.Timer(), len(train_iter)
net = nn.DataParallel(net, devices).to(devices[0])
animator = d2l.Animator(xlabel='epoch', xlim=[1, epochs], ylim=[0, 1],
legend=['train loss', 'train acc', 'test acc'])
for epoch in range(epochs):
# 4个维度:累加存储训练损失,训练准确度,样本数,样本数
accumulator = d2l.Accumulator(4)
for i, (X, y) in enumerate(train_iter):
timer.start()
train_batch_loss, train_batch_accuracy = train_batch_ch13(net, X, y, loss, optim, devices)
accumulator.add(train_batch_loss, train_batch_accuracy, y.shape[0], y.numel())
timer.stop()
if (i + 1) % (num_batchs // 5) == 0 or i == num_batchs - 1:
animator.add(epoch + (i + 1) / num_batchs,
(accumulator[0] / accumulator[2], accumulator[1] / accumulator[3], None))
test_accuracy = d2l.evaluate_accuracy_gpu(net, test_iter)
animator.add(epoch + 1, (None, None, test_accuracy))
print(f'loss {accumulator[0] / accumulator[2]:.3f},train acc {accumulator[1] / accumulator[3]},test acc {test_accuracy:.3f}')
print(f'{accumulator[2] * epochs / timer.sum() :.1f}个样本/sec ,在{str(devices[0])}')
备注:仅学习使用无需任何打赏