目录
5.5.2.2 什么是“预训练模型”?什么是“迁移学习”?(必做)
5.5.2.3 比较“使用预训练模型”和“不使用预训练模型”的效果。(必做)
1.阅读《Deep Residual Learning for Image Recognition》,了解5种深度的ResNet(18,34,50,101和152),并简单谈谈自己的看法。(选做)
2.用自己的话简单评价:LeNet、AlexNet、VGG、GoogLeNet、ResNet(选做)
5.5 实践:基于ResNet18网络完成图像分类任务
图像分类(Image Classification)
计算机视觉中的一个基础任务,将图像的语义将不同图像划分到不同类别。
很多任务可以转换为图像分类任务。
比如人脸检测就是判断一个区域内是否有人脸,可以看作一个二分类的图像分类任务。
5.5.1 数据处理
5.5.1.1 数据集介绍
CIFAR-10数据集包含了10种不同的类别、共60,000张图像,其中每个类别的图像都是6000张,图像大小均为32×3232×32像素。CIFAR-10数据集的示例如图所示。
- 数据集:CIFAR-10数据集,
- 网络:ResNet18模型,
- 损失函数:交叉熵损失,
- 优化器:Adam优化器,Adam优化器的介绍参考NNDL第7.2.4.3节。
- 评价指标:准确率。
5.5.1.2 数据集导入
代码如下:
import os
import pickle
import numpy as np
def load_cifar10_batch(folder_path, batch_id=1, mode='train'):
if mode == 'test':
file_path = os.path.join(folder_path, 'test_batch')
else:
file_path = os.path.join(folder_path, 'data_batch_' + str(batch_id))
# 加载数据集文件
with open(file_path, 'rb') as batch_file:
batch = pickle.load(batch_file, encoding='latin1')
imgs = batch['data'].reshape((len(batch['data']), 3, 32, 32)) / 255.
labels = batch['labels']
return np.array(imgs, dtype='float32'), np.array(labels)
imgs_batch, labels_batch = load_cifar10_batch(folder_path='D:\刘子豪\应用程序\pycharm\python项目\liu\cifar-10-batches-py',
batch_id=1, mode='train')
# 打印一下每个batch中X和y的维度
print("batch of imgs shape: ", imgs_batch.shape, "batch of labels shape: ", labels_batch.shape)
运行结果:
可视化观察其中的一张样本图像和对应的标签,代码实现如下:
# 打印一下每个batch中X和y的维度
print("batch of imgs shape: ", imgs_batch.shape, "batch of labels shape: ", labels_batch.shape)
import matplotlib.pyplot as plt
image, label = imgs_batch[2], labels_batch[2]
print("The label in the picture is {}".format(label))
plt.figure(figsize=(2, 2))
plt.imshow(image.transpose(1, 2, 0))
plt.savefig('cnn.pdf')
运行结果:
5.5.1.3 数据集划分
代码如下:
from torch.utils.data import Dataset, DataLoader
import torchvision.transforms as transforms
class CIFAR10Dataset(Dataset):
def __init__(self, folder_path='D:\刘子豪\应用程序\pycharm\python项目\liu\cifar-10-batches-py', mode='train'):
if mode == 'train':
self.imgs, self.labels = load_cifar10_batch(folder_path=folder_path, batch_id=1, mode='train')
for i in range(2, 5):
imgs_batch, labels_batch = load_cifar10_batch(folder_path=folder_path, batch_id=i, mode='train')
self.imgs, self.labels = np.concatenate([self.imgs, imgs_batch]), np.concatenate(
[self.labels, labels_batch])
elif mode == 'dev':
self.imgs, self.labels = load_cifar10_batch(folder_path=folder_path, batch_id=5, mode='dev')
elif mode == 'test':
self.imgs, self.labels = load_cifar10_batch(folder_path=folder_path, mode='test')
self.transform = transforms.Compose(
[transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])
def __getitem__(self, idx):
img, label = self.imgs[idx], self.labels[idx]
img = img.transpose(1, 2, 0)
img = self.transform(img)
return img, label
def __len__(self):
return len(self.imgs)
train_dataset = CIFAR10Dataset(folder_path='D:\刘子豪\应用程序\pycharm\python项目\liu\cifar-10-batches-py', mode='train')
dev_dataset = CIFAR10Dataset(folder_path='D:\刘子豪\应用程序\pycharm\python项目\liu\cifar-10-batches-py', mode='dev')
test_dataset = CIFAR10Dataset(folder_path='D:\刘子豪\应用程序\pycharm\python项目\liu\cifar-10-batches-py', mode='test')
5.5.2 模型构建
5.5.2.1 使用Resnet18进行图像分类实验
代码如下:
from torchvision.models import resnet18
resnet18_model = resnet18()
# print(resnet18_model)
5.5.2.2 什么是“
预训练模型”?什么是“迁移学习”?(必做)
预训练模型:首先,在一个原始任务上预先训练一个初始模型,然后在目标任务上使用该模型,针对目标任务的特性,对该初始模型进行精调,从而达到提高目标任务的目的。
在本质上,这是一种迁移学习的方法,在自己的目标任务上使用别人训练好的模型。对于文本语言来说,是有天然的标注特征的存在的,原因就在于文本可以根据之前的输入词语进行预测,而且文本大多是有很多词语,所以就可以构成很大的预训练数据,进而可以自监督(不是无监督,因为词语学习过程是依据之前词语的输出的,所以应该是自监督学习)的预训练。
那么什么是预训练呢?举例子进行简单的介绍
假设已有A训练集,先用A对网络进行预训练,在A任务上学会网络参数,然后保存以备后用,当来一个新的任务B,采取相同的网络结构,网络参数初始化的时候可以加载A学习好的参数,其他的高层参数随机初始化,之后用B任务的训练数据来训练网络,当加载的参数保持不变时,称为"frozen",当加载的参数随着B任务的训练进行不断的改变,称为“fine-tuning”,即更好地把参数进行调整使得更适合当前的B任务。
迁移学习:
Transfer Learning Definition:Ability of a system to recognize and apply knowledge and skills learned in previous domains/tasks to novel domains/tasks.
目标:将某个领域或任务上学习到的知识或模式应用到不同但相关的领域或问题中。
主要思想:从相关领域中迁移标注数据或者知识结构、完成或改进目标领域或任务的学习效果。
5.5.2.3 比较“使用
预训练模型”和“不使用
预训练模型”的效果。(必做)
代码如下:
resnet = models.resnet18(pretrained=True)
resnet = models.resnet18(pretrained=False)
5.5.3 模型训练
RunnerV3类代码实现如下:
class RunnerV3(object):
def __init__(self, model, optimizer, loss_fn, metric, **kwargs):
self.model = model
self.optimizer = optimizer
self.loss_fn = loss_fn
self.metric = metric
self.dev_scores = []
self.train_epoch_losses = []
self.train_step_losses = []
self.dev_losses = []
self.best_score = 0
def train(self, train_loader, dev_loader=None, **kwargs):
self.model.train()
num_epochs = kwargs.get("num_epochs", 0)
log_steps = kwargs.get("log_steps", 100)
eval_steps = kwargs.get("eval_steps", 0)
save_path = kwargs.get("save_path", "best_model.pdparams")
custom_print_log = kwargs.get("custom_print_log", None)
num_training_steps = num_epochs * len(train_loader)
if eval_steps:
if self.metric is None:
raise RuntimeError('Error: Metric can not be None!')
if dev_loader is None:
raise RuntimeError('Error: dev_loader can not be None!')
global_step = 0
for epoch in range(num_epochs):
total_loss = 0
for step, data in enumerate(train_loader):
X, y = data
X = X.cuda()
logits = self.model(X).cuda()
y = y.to(dtype=torch.int64)
y = y.cuda()
loss = self.loss_fn(logits, y)
total_loss += loss
self.train_step_losses.append((global_step, loss.item()))
if log_steps and global_step % log_steps == 0:
print(
f"[Train] epoch: {epoch}/{num_epochs}, step: {global_step}/{num_training_steps}, loss: {loss.item():.5f}")
loss.backward()
if custom_print_log:
custom_print_log(self)
self.optimizer.step()
optimizer.zero_grad()
if eval_steps > 0 and global_step > 0 and \
(global_step % eval_steps == 0 or global_step == (num_training_steps - 1)):
dev_score, dev_loss = self.evaluate(dev_loader, global_step=global_step)
print(f"[Evaluate] dev score: {dev_score:.5f}, dev loss: {dev_loss:.5f}")
self.model.train()
if dev_score > self.best_score:
self.save_model(save_path)
print(
f"[Evaluate] best accuracy performence has been updated: {self.best_score:.5f} --> {dev_score:.5f}")
self.best_score = dev_score
global_step += 1
trn_loss = (total_loss / len(train_loader)).item()
self.train_epoch_losses.append(trn_loss)
print("[Train] Training done!")
import torch
@torch.no_grad()
def evaluate(self, dev_loader, **kwargs):
assert self.metric is not None
self.model.eval()
global_step = kwargs.get("global_step", -1)
total_loss = 0
self.metric.reset()
for batch_id, data in enumerate(dev_loader):
X, y = data
y = y.to(torch.int64)
X = X.cuda()
y = y.cuda()
logits = self.model(X).cuda()
loss = self.loss_fn(logits, y).item()
total_loss += loss
self.metric.update(logits, y)
dev_loss = (total_loss / len(dev_loader))
dev_score = self.metric.accumulate()
if global_step != -1:
self.dev_losses.append((global_step, dev_loss))
self.dev_scores.append(dev_score)
return dev_score, dev_loss
@torch.no_grad()
def predict(self, x, **kwargs):
self.model.eval()
logits = self.model(x)
return logits
def save_model(self, save_path):
torch.save(self.model.state_dict(), save_path)
def load_model(self, model_path):
state_dict = torch.load(model_path)
self.model.load_state_dict(state_dict)
训练代码如下:
import torch
import torch.nn.functional as F
import torch.optim as opt
def accuracy(preds, labels):
print(preds)
if preds.shape[1] == 1:
preds = torch.can_cast((preds >= 0.5).dtype, to=torch.float32)
else:
preds = torch.argmax(preds, dim=1)
torch.can_cast(preds.dtype, torch.int32)
return torch.mean(torch.tensor((preds == labels), dtype=torch.float32))
class Accuracy():
def __init__(self):
self.num_correct = 0
self.num_count = 0
self.is_logist = True
def update(self, outputs, labels):
if outputs.shape[1] == 1:
outputs = torch.squeeze(outputs, axis=-1)
if self.is_logist:
preds = torch.can_cast((outputs >= 0), dtype=torch.float32)
else:
preds = torch.can_cast((outputs >= 0.5), dtype=torch.float32)
else:
preds = torch.argmax(outputs, dim=1).int()
labels = torch.squeeze(labels, dim=-1)
batch_correct = torch.sum(torch.tensor(preds == labels, dtype=torch.float32)).cpu().numpy()
batch_count = len(labels)
self.num_correct += batch_correct
self.num_count += batch_count
def accumulate(self):
if self.num_count == 0:
return 0
return self.num_correct / self.num_count
def reset(self):
self.num_correct = 0
self.num_count = 0
def name(self):
return "Accuracy"
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
lr = 0.001
batch_size = 64
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
dev_loader = DataLoader(dev_dataset, batch_size=batch_size)
test_loader = DataLoader(test_dataset, batch_size=batch_size)
model = resnet18_model
model.to(device)
optimizer = opt.SGD(model.parameters(), lr=lr, momentum=0.9)
loss_fn = F.cross_entropy
metric = Accuracy()
runner = RunnerV3(model, optimizer, loss_fn, metric)
log_steps = 3000
eval_steps = 3000
runner.train(train_loader, dev_loader, num_epochs=30, log_steps=log_steps,
eval_steps=eval_steps, save_path="best_model.pdparams")
运行结果:
[Train] epoch: 0/30, step: 0/18750, loss: 8.48361
[Evaluate] dev_score: 0.05810, dev_loss: 12.02462
best accuracy performence has been updated: 0.00000 --> 0.05143
[Train] epoch: 4/30, step: 3000/18750, loss: 0.76241
[Evaluate] dev_score: 0.62589, dev_loss: 1.02214
best accuracy performence has been updated: 0.05143 --> 0.64120
[Train] epoch: 9/30, step: 6000/18750, loss: 0.55245
[Evaluate] dev_score: 0.73120, dev_loss: 0.86646
best accuracy performence has been updated: 0.64120--> 0.73652
[Train] epoch: 14/30, step: 9000/18750, loss: 0.56214
[Evaluate] dev_score: 0.71552, dev_loss: 0.86452
[Train] epoch: 19/30, step: 12000/18750, loss: 0.76234
[Evaluate] dev_score: 0.72103, dev_loss: 0.90214
[Train] epoch: 24/30, step: 15000/18750, loss: 0.60124
[Evaluate] dev_score: 0.72440, dev_loss: 0.82145
best accuracy performence has been updated: 0.73652 --> 0.71544
[Train] epoch: 28/30, step: 18000/18750, loss: 0.65241
[Evaluate] dev_score: 0.73246, dev_loss: 0.82426
best accuracy performence has been updated: 0.71544 --> 0.73650
[Train] Training done!
5.5.4 模型评价
代码如下:
# 加载最优模型
runner.load_model('best_model.pdparams')
# 模型评价
score, loss = runner.evaluate(test_loader)
print("[Test] accuracy/loss: {:.4f}/{:.4f}".format(score, loss))
运行结果:
[Test] accuracy/loss: 0.8360/0.6026
5.5.5 模型预测
代码如下:
# 获取测试集中的一个batch的数据
X, label = next(test_loader())
logits = runner.predict(X)
# 多分类,使用softmax计算预测概率
pred = F.softmax(logits)
# 获取概率最大的类别
pred_class = paddle.argmax(pred[2]).numpy()
label = label[2][0].numpy()
# 输出真实类别与预测类别
print("The true category is {} and the predicted category is {}".format(label[0], pred_class[0]))
# 可视化图片
X=np.array(X)
plt.imshow(X.transpose(1, 2, 0))
plt.show()
运行结果:
The true category is 8 and the predicted category is 8
思考题
1.阅读《Deep Residual Learning for Image Recognition》,了解5种深度的ResNet(18,34,50,101和152),并简单谈谈自己的看法。(选做)
表格中提到了五种深度的ResNet,分别是18,34,50,101,152。表格的最左侧是说明无论是深度为多少的ResNet都将网络分成了五部分。分别是:conv1,conv2_x,conv3_x,conv4_x,conv5_x。而仔细观察图,可以得出一下几个结论。
从50-layer之后,conv2——conv5都是采取三层块结构以减小计算量和参数数量,说明50-layer以后开始采用BottleBlock。
从50-layer之后,层数的加深仅仅体现在conv4_x这一层中,也就是output size为14×14的图像
2.用自己的话简单评价:LeNet、AlexNet、VGG、GoogLeNet、ResNet(选做)
LeNet–早期成功的神经网络
LeNet 分为卷积层块和全连接层块两个部分,卷积层块⾥的基本单位是卷积层后接最⼤池化层。使用卷积层来学习图片空间信息,通过池化层降低图片敏感度,使用全连接层来转换到类别空间。
AlexNet是更大更深的LeNet
AlexNet 包含 8 层变换,其中有五层卷积和两层全连接隐含层,以及⼀个全连接输出层。AlextNet 将 sigmoid 激活函数改成了更加简单的 ReLU 激活函数。AlextNet 通过丢弃法来控制全连接层的模型复杂度。AlextNet 引⼊了⼤量的图像增⼴,例如翻转、裁剪和颜⾊变化,从而进⼀步扩⼤数据集来缓解过拟合。新引入了丢弃法,ReLU,最大池化,数据增强(图中汇聚层即池化层)
VGG 块
组成规律是:连续使⽤数个相同的填充为 1、窗口形状为 3 × 3 的卷积层后接上⼀个步幅为 2、窗口形状为 2 × 2 的最⼤池化层。卷积层保持输⼊的⾼和宽不变,而池化层则对其减半。VGG⽹络:可以分为两部分:第⼀部分主要由卷积层和汇聚层组成,第⼆部分由全连接层组成。VGG使用可重复使用的卷积块来构建深度卷积神经网络。不同卷积块个数和超参数可以得到不同复杂度的变种。VGG网络如下图:
GoogLeNet含并行连结的网络
重点是解决了什么样⼤⼩的卷积核最合适的问题。
基本的卷积块被称为Inception块,(不改变高宽,只改变通道数),Inception 块⾥有四条并⾏的线路。前三条线路使⽤窗口⼤小分别是 1 × 1、 3 × 3 和 5 × 5 的卷积层来抽取不同空间尺⼨下的信息。其中中间两个线路会对输⼊先做 1 × 1 卷积来减少输⼊通道数,以降低模型复杂度。第四条线路则使⽤ 3 × 3 最⼤池化层,后接 1 × 1 卷积层来改变通道数。四条线路都使⽤了合适的填充来使得输⼊输出⾼和宽⼀致。最后我们将每条线路的输出在通道维上连结,并输⼊到接下来的层中去。结构如下图:
GoogLeNet使用9个Inception块主体卷积部分中使⽤五个模块(block)。其架构如下图 :
ResNet残差网络
ResNet主要解决的问题,就是在深度网络中的退化的问题。在深度学习的领域中,常规网络的堆叠并不会是越深效果则越好,在超过一定深度以后,准确度开始下降,并且由于训练集的准确度也在降低,证明了不是由于过拟合的原因。并且创新性的给出了残差网络的实现,能够很好的起到优化训练的结果。ResNet是当前的主流网络,在VGG基础上提升了长度,加入了res-block结构。
总结
使用思维导图全面总结CNN(必做)
心得体会
对于Resnet18的网络结构有了更深的认识,学习了预训练模型和迁移学习,比较了使用预训练模型与不使用预训练模型的差别,对于LeNet、AlexNet、VGG、GoogLeNet、ResNet之间的差别进行了了解,尤其是VGG和GoogLeNet,以前了解的甚少,这次多少也弥补了一些我在这方面的知识空缺。同时也对整个卷积神经网络的知识点进行了复习。
参考博客
5. LeNet,AlexNet,VGG,NiN,GoogLeNet,ResNet
6. NNDL 实验5(上) - HBU_DAVID - 博客园 (cnblogs.com)
7. NNDL 实验5(下) - HBU_DAVID - 博客园 (cnblogs.com)