动手学深度学习-39

敖炜 Lv5

实战Kaggle比赛,图像分类(CIFAR-10)

这里将从原始图像文件开始,然后逐步组织、读取并将它们转换为张量格式

获取并组织数据集

比赛数据集分为训练集和测试集,其中训练集包含50000张、测试集包含300000张图像。在测试集中,10000张图像将被用于评估,而剩下的290000张图像将不会被进行评估,包含它们只是为了防止手动标记测试集并提交标记结果(防作弊)。两个数据集中的图像都是png格式,高度和宽度均为32像素并有三个颜色通道(RGB)。这些图片共涵盖10个类别:飞机、汽车、鸟类、猫、鹿、狗、青蛙、马、船和卡车。

下载数据集

为了便于入门,使用包含前1000个训练图像和5个随机测试图像的数据集的小规模样本。要使用Kaggle竞赛的完整数据集,需要将以下demo变量设置为False

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import collections
import math
import os
import shutil
import pandas as pd
import torch
import torchvision
from torch import nn
from d2l import torch as d2l

#@save
d2l.DATA_HUB["cifar10_tiny"] = (d2l.DATA_URL + "kaggle_cifar10_tiny.zip", '2068874e4b9a9f0fb07ebe0ad2b29754449ccacd')

# 如果使用完整的Kaggle竞赛的数据集,设置demo为False
demo = True

if demo:
data_dir = d2l.download_extract("cifar10_tiny")
else:
data_dir = "../data/cifar-10/"

整理数据集

需要整理数据集来训练和测试模型。首先,我们用以下函数读取CSV文件中的标签,它返回一个字典,该字典将文件名中不带扩展名的部分映射到其标签。

1
2
3
4
5
6
7
8
9
10
11
12
13
#@save
def read_csv_labels(fname):
"""读取fname来给标签字典返回一个文件名"""
with open(fname, "r") as f:
# 跳过文件头行(列名)
line = f.readlines()[1:]

tokens = [l.rstrip().split(",") for l in lines]
return dict(((name, label) for name, label in tokens))

labels = read_csv_labels(os.path.join(data_dir, "trainLabels.csv"))
print("# 训练样本 :", len(labels))
print("# 类别 :", len(set(labels.values())))

定义reorg_train_valid函数来将验证集从原始的训练集中拆分出来。此函数中的参数valid_ratio是验证集中的样本数与原始训练集中的样本数之比。更具体地说,令等于样本最少的类别中的图像数量,而是比率。验证集将为每个类别拆分出张图像。让我们以valid_ratio=0.1为例,由于原始的训练集有50000张图像,因此train_valid_test/train路径中将有45000张图像用于训练,而剩下5000张图像将作为路径train_valid_test/valid中的验证集。组织数据集后,同类别的图像将被放置在同一文件夹下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#@save
def copyfile(filename, target_dir):
"""将文件复制到目标目录"""
os.makedirs(target_dir, exist_ok=True)
shutil.copy(filename, target_dir)

#@save
def reorg_train_valid(data_dir, labels, valid_ratio):
"""将验证集从原始的训练集中拆分出来"""
# 训练数据集中样本最少的类别中的样本数
n = collections.Counter(labels.values()).most_common()[-1][1]
# 验证集中每个类别的样本数
n_valid_per_label = max(1, math.floor(n * valid_ratio))
label_count = {}

for train_file in os.listdir(os.path.join(data_dir, "train")):
label = labels[train_file.split(".")[0]]
fname = os.path.join(data_dir, "train", train_file)
copyfile(fname, os.path.join(data_dir, "train_valid_test", "train_valid", label))

if label not in label_count or label_count[label] < n_valid_per_label:
copyfile(fname, os.path.join(data_dir, "rain_valid_test", "valid", label))

label_count[label] = label_count.get(label, 0) + 1
else:
copyfile(fname, os.path.join(data_dir, "train_valid_test", "train", label))

return n_valid_per_label

下面的reorg_test函数用来在预测期间整理测试集,以方便读取

1
2
3
4
5
6
#@save
def reorg_test(data_dir):
"""在预测期间整理测试集,以方便读取"""
for test_file in os.listdir(os.path.join(data_dir, "test")):
copyfile(os.path.join(data_dir, "test", test_file),
os.path.join(data_dir, 'train_valid_test', 'test', 'unknown'))

最后,我们使用一个函数来调用前面定义的函数read_csv_labelsreorg_train_validreorg_test

1
2
3
4
def reorg_cifar10_data(data_dir, valid_ratio):
labels = read_csv_labels(os.path.join(data_dir, "trainLabels.csv"))
reorg_train_valid(data_dir, labels, valid_ratio)
reorg_test(data_dir)

在这里,我们只将样本数据集的批量大小设置为32。在实际训练和测试中,应该使用Kaggle竞赛的完整数据集,并将batch_size设置为更大的整数,例如128。我们将10%的训练样本作为调整超参数的验证集。

1
2
3
batch_size = 32 if demo else 128
valid_ratio = 0.1
reorg_cifar10_data(data_dir, valid_ratio)

图像增广

我们使用图像增广来解决过拟合的问题。例如在训练中,我们可以随机水平翻转图像。我们还可以对彩色图像的三个RGB通道执行标准化。下面,我们列出了其中一些可以调整的操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
transform_train = torchvision.transforms.Compose([
# 在高度和宽度上将图像放大到40像素的正方形
torchvision.transforms.Resize(40),
# 随机裁剪出一个高度和宽度均为40像素的正方形图像,
# 生成一个面积为原始图像面积0.64~1倍的小正方形,
# 然后将其缩放为高度和宽度均为32像素的正方形
torchvision.transforms.RandomResizedCrop(32, scale=(0.64, 1.0), ratio=(1.0, 1.0)),
torchvision.transforms.RandomHorizontalFlip(),
torchvision.transforms.ToTensor(),
# 标准化图像的每个通道
torchvision.transforms.Normalize([0.4914, 0.4822, 0.4465],
[0.2023, 0.1994, 0.2010])]
)

# 在测试期间,我们只对图像执行标准化,以消除评估结果中的随机性。

transform_test = torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize([0.4914, 0.4822, 0.4465],
[0.2023, 0.1994, 0.2010])])

读取数据集

接下来,读取由原始图像组成的数据集,每个样本都包括一张图片和一个标签

1
2
3
train_ds, train_valid_ds = [torchvision.datasets.ImageFolder(os.path.join(data_dir, "train_valid_test", folder), transform=transform_train) for folder in ["train", "train_valid"]]

valid_ds, test_ds = [torchvision.datasets.ImageFolder(os.path.join(data_dir, "train_valid_test", folder), transform=transform_test) for folder in ["valid", "test"]]

在训练期间,我们需要指定上面定义的所有图像增广操作。当验证集在超参数调整过程中用于模型评估时,不应引入图像增广的随机性。
在最终预测之前,我们根据训练集和验证集组合而成的训练模型进行训练,以充分利用所有标记的数据。

1
2
3
4
5
6
7
8
train_iter, train_valid_iter = [torch.utils.data.DataLoader(dataset, batch_size, shuffle=True, drop_last=True) for dataset in (train_ds, train_valid_ds)]

# drop_last为True表示如果最后一个batch不满足所要的需求大小,将其丢掉
valid_iter = torch.utils.data.DataLoader(valid_ds, batch_size, shuffle=False,
drop_last=True)

test_iter = torch.utils.data.DataLoader(test_ds, batch_size, shuffle=False,
drop_last=False)

定义模型

1
2
3
4
5
6
def get_net():
num_classes = 10
net = d2l.resnet18(num_classer, 3) # 3表示通道
return net

loss = nn.CrossEntropyLoss(reduction="none")

定义训练函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# lr_period表示每隔多少时间(epoch)将lr减小, lr_decay表示lr减小多少(decay * lr)
def train(net, train_iter, valid_iter, num_epochs, lr, wd, devices, lr_period, lr_decay):
trainer = torch.optim.SGD(net.parameters(), lr=lr, momentum=0.9, weight_dacay=wd)
scheduler = torch.optim.lr_scheduler.StepLR(trainer, lr_period, lr_decay)
num_batchs, timer = len(train_iter), d2l.Timer()

legend = ['train loss', 'train acc']

if valid_iter is not None:
legend.append("valid acc")

animator = d2l.Animator(xlabel="epoch", xlim=[1, num_epochs], legend=legend)

net = nn.DataParallel(net, device_ids=devices).to(devices[0])

for epoch in range(num_epochs):
net.train()
metric = d2l.Accumulator(3)
for i, (features, labels) in enumerate(train_iter):
timer.start()
l, acc = d2l.train_batch_ch13(net, features, labels, loss, trainer, devices)
metric.add(l, acc, labels.shape[0])
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[2], None))

if valid_iter is not None:
valid_acc = d2l.evaluate_acuracy_gpu(net, valid_iter)
animator.add(epoch + 1, (None, None, valid_acc))

scheduler.step()

measures = (f'train loss {metric[0] / metric[2]:.3f}, '
f'train acc {metric[1] / metric[2]:.3f}')
if valid_iter is not None:
measures += f', valid acc {valid_acc:.3f}'
print(measures + f'\n{metric[2] * num_epochs / timer.sum():.1f}'
f' examples/sec on {str(devices)}')

训练和验证模型

1
2
3
devices, num_epochs, lr, wd = d2l.try_all_gpus(), 20, 2e-4, 5e-4
lr_period, lr_decay, net = 4, 0.9, get_net()
train(net, train_iter, valid_iter, num_epochs, lr, wd, devices, lr_period,, lr_decay)

在 Kaggle 上对测试集进行分类并提交结果

在通过验证集调得具有超参数的满意的模型后,我们使用所有标记的数据(包括验证集)来重新训练模型并对测试集进行分类。

1
2
3
4
5
6
7
8
9
10
11
12
net, preds = get_net(), []
train(net, train_valid_iter, None, num_epochs, lr, wd, devices, lr_period, lr_decay)

for X, _ in test_iter:
y_hat = net(X.to(device[0]))
preds.extend(y_hat.argmax(dim=1).type(torch.int32).cpu().numpy())

sorted_ids = list(range(1, len(test_ds) + 1))
sorted_ids.sort(key=lambda x: str(x))
df = pd.DataFrame({'id': sorted_ids, 'label': preds})
df['label'] = df['label'].apply(lambda x: train_valid_ds.classes[x])
df.to_csv('submission.csv', index=False)

小结

  • 将包含原始图像文件的数据集组织为所需格式后,我们可以读取它们。
  • 我们可以在图像分类竞赛中使用卷积神经网络和图像增广。
  • 标题: 动手学深度学习-39
  • 作者: 敖炜
  • 创建于 : 2023-09-03 17:08:15
  • 更新于 : 2024-04-19 09:29:16
  • 链接: https://ao-wei.github.io/2023/09/03/动手学深度学习-39/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论