如今的ResNet已经使用的非常普遍了,标准的模型有
本篇博客主要介绍如何自行实现ResNet,毕竟现在这些主流模型已经被各大框架封装成了Model Zoo,可以实现一句话调用模型,甚至还提供了各种版本的预训练模型可供加载,可以选择进行在何处进行截取,便于实现自定义分类器。以下分为tensorflow与pytorch分解介绍实现。
一、Tensorflow
不得不说,tensorflow虽然用的多,但是质量不高啊,很多人写的就是一坨屎。。这里选择一个还不错的进行展示。
关于Resnet残差网络的介绍已经非常多了,这里就不在赘述.使用Tensorflow写了一个简单的Resnet,对CIFAR-10数据集进行十分类.关键步骤都写了详细注释,虽然最后的精度不高,但还是学习Resnet的思想为主.
import tensorflow as tf
import os
import numpy as np
import pickle
# 文件存放目录
CIFAR_DIR = "./cifar-10-batches-py"
def load_data(filename):
'''read data from data file'''
with open(filename, 'rb') as f:
data = pickle.load(f, encoding='bytes') # python3 需要添加上encoding='bytes'
return data[b'data'], data[b'labels'] # 并且 在 key 前需要加上 b
class CifarData:
def __init__(self, filenames, need_shuffle):
'''参数1:文件夹 参数2:是否需要随机打乱'''
all_data = []
all_labels = []
for filename in filenames:
# 将所有的数据,标签分别存放在两个list中
data, labels = load_data(filename)
all_data.append(data)
all_labels.append(labels)
# 将列表 组成 一个numpy类型的矩阵!!!!
self._data = np.vstack(all_data)
# 对数据进行归一化, 尺度固定在 [-1, 1] 之间
self._data = self._data / 127.5 - 1
# 将列表,变成一个 numpy 数组
self._labels = np.hstack(all_labels)
# 记录当前的样本 数量
self._num_examples = self._data.shape[0]
# 保存是否需要随机打乱
self._need_shuffle = need_shuffle
# 样本的起始点
self._indicator = 0
# 判断是否需要打乱
if self._need_shuffle:
self._shffle_data()
def _shffle_data(self):
# np.random.permutation() 从 0 到 参数,随机打乱
p = np.random.permutation(self._num_examples)
# 保存 已经打乱 顺序的数据
self._data = self._data[p]
self._labels = self._labels[p]
def next_batch(self, batch_size):
'''return batch_size example as a batch'''
# 开始点 + 数量 = 结束点
end_indictor = self._indicator + batch_size
# 如果结束点大于样本数量
if end_indictor > self._num_examples:
if self._need_shuffle:
# 重新打乱
self._shffle_data()
# 开始点归零,从头再来
self._indicator = 0
# 重新指定 结束点. 和上面的那一句,说白了就是重新开始
end_indictor = batch_size # 其实就是 0 + batch_size, 把 0 省略了
else:
raise Exception("have no more examples")
# 再次查看是否 超出边界了
if end_indictor > self._num_examples:
raise Exception("batch size is larger than all example")
# 把 batch 区间 的data和label保存,并最后return
batch_data = self._data[self._indicator:end_indictor]
batch_labels = self._labels[self._indicator:end_indictor]
self._indicator = end_indictor
return batch_data, batch_labels
# 拿到所有文件名称
train_filename = [os.path.join(CIFAR_DIR, 'data_batch_%d' % i) for i in range(1, 6)]
# 拿到标签
test_filename = [os.path.join(CIFAR_DIR, 'test_batch')]
# 拿到训练数据和测试数据
train_data = CifarData(train_filename, True)
test_data = CifarData(test_filename, False)
def residual_block(x, output_channel):
'''
定义残差块儿
:param x: 输入tensor
:param output_channel: 输出的通道数
:return: tensor
需要注意的是:每经过一个stage,通道数就要 * 2
在同一个stage中,通道数是没有变化的
'''
input_channel = x.get_shape().as_list()[-1] # 拿出 输入 tensor 的 最后一维:也就是通道数
if input_channel * 2 == output_channel:
increase_dim = True
strides = (2, 2) #
elif input_channel == output_channel:
increase_dim = False
strides = (1, 1)
else:
raise Exception("input channel can't match output channel")
conv1 = tf.layers.conv2d(x,
output_channel,
(3, 3),
strides = strides,
padding = 'same',
activation = tf.nn.relu,
name = 'conv1'
)
conv2 = tf.layers.conv2d(conv1,
output_channel,
(3, 3),
strides = (1, 1), # 因为 上一层 卷积已经进行过降采样,故这里不需要
padding = 'same',
activation = tf.nn.relu,
name = 'conv2'
)
if increase_dim: # 需要使用降采样
# pooled_x 数据格式 [ None, image_width, image_height, channel ]
# 要求格式 [ None, image_width, image_height, channel * 2 ]
pooled_x = tf.layers.average_pooling2d(x,
(2, 2), # size
(2, 2), # stride
padding = 'valid'
)
'''
如果输出通道数是输入的两倍的话,需要增加通道数量.
maxpooling 只能降采样,而不能增加通道数,
所以需要单独增加通道数
'''
padded_x = tf.pad(pooled_x, # 参数 2 ,在每一个通道上 加 pad
[
[ 0, 0 ],
[ 0, 0 ],
[ 0, 0 ],
[input_channel // 2, input_channel // 2] # 实际上就是 2倍input_channel,需要均分开
]
)
else:
padded_x = x
output_x = conv2 + padded_x # 就是 公式: H(x) = F(x) + x
return output_x
def res_net(x, num_residual_blocks, num_filter_base, class_num):
'''
残差网络主程序
:param x: 输入tensor
:param num_residual_blocks: 每一个stage有多少残差块儿 eg: list [3, 4, 6, 2] 及每一个stage上的残差块儿数量
:param num_filter_base: 最初的通道数
:param class_num: 所需要的分类数
:return: tensor
'''
num_subsampling = len(num_residual_blocks) # num_subsampling 为 stage 个数
layers = [] # 保存每一个残差块的输出
# x: [ None, width, height, channel] -> [width, height, channel]
input_size = x.get_shape().as_list()[1:]
# 首先,开始第一个卷积层
with tf.variable_scope('conv0'):
conv0= tf.layers.conv2d(x,
num_filter_base,
(3, 3),
strides = (1, 1),
padding = 'same',
name = 'conv0'
)
layers.append(conv0)
# 根据 模型,此处应有一个 pooling,但是 cifar-10 数据集很小,所以不再做 pool
# num_subsampling = 4, sample_id = [0, 1, 2, 3]
for sample_id in range(num_subsampling):
for i in range(num_residual_blocks[sample_id]):
with tf.variable_scope('conv%d_%d' % (sample_id, i)):
conv = residual_block(layers[-1],
num_filter_base * ( 2 ** sample_id ) # 每一个stage都是之前的2倍
)
layers.append(conv)
# 最后就到了 average pool, 1000维 全连接, 这一步
with tf.variable_scope('fc'):
# layer[-1].shape: [None, width, height, channel]
# kernal_size = image_width, image_height
global_pool = tf.reduce_mean(layers[-1], [1, 2]) # 求平均值函数,参数二 指定 axis
# global_pool的shape是(?, 128)
# 这里需要解释一下,对第二维,第三维求平均值,实际上就是对每一个feature map求一个平均值,一共有128个特征图.
# 所以维度从四维,降低到了两维
logits = tf.layers.dense(global_pool, class_num)
layers.append(logits)
return layers[-1]
# 设计计算图
# 形状 [None, 3072] 3072 是 样本的维数, None 代表位置的样本数量
x = tf.placeholder(tf.float32, [None, 3072])
# 形状 [None] y的数量和x的样本数是对应的
y = tf.placeholder(tf.int64, [None])
# [None, ], eg: [0, 5, 6, 3]
x_image = tf.reshape(x, [-1, 3, 32, 32])
# 将最开始的向量式的图片,转为真实的图片类型
x_image = tf.transpose(x_image, perm= [0, 2, 3, 1])
y_ = res_net(x_image, [2, 3, 2], 32, 10)
# 使用交叉熵 设置损失函数
loss = tf.losses.sparse_softmax_cross_entropy(labels = y, logits = y_)
# 该api,做了三件事儿 1. y_ -> softmax 2. y -> one_hot 3. loss = ylogy
# 预测值 获得的是 每一行上 最大值的 索引.注意:tf.argmax()的用法,其实和 np.argmax() 一样的
predict = tf.argmax(y_, 1)
# 将布尔值转化为int类型,也就是 0 或者 1, 然后再和真实值进行比较. tf.equal() 返回值是布尔类型
correct_prediction = tf.equal(predict, y)
# 比如说第一行最大值索引是6,说明是第六个分类.而y正好也是6,说明预测正确
# 将上句的布尔类型 转化为 浮点类型,然后进行求平均值,实际上就是求出了准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float64))
with tf.name_scope('train_op'): # tf.name_scope() 定义该变量的命名空间
train_op = tf.train.AdamOptimizer(1e-3).minimize(loss) # 将 损失函数 降到 最低
# 初始化变量
init = tf.global_variables_initializer()
batch_size = 20
train_steps = 100000
test_steps = 100
with tf.Session() as sess:
sess.run(init) # 注意: 这一步必须要有!!
# 开始训练
for i in range(train_steps):
# 得到batch
batch_data, batch_labels = train_data.next_batch(batch_size)
# 获得 损失值, 准确率
loss_val, acc_val, _ = sess.run([loss, accuracy, train_op], feed_dict={x:batch_data, y:batch_labels})
# 每 500 次 输出一条信息
if (i+1) % 500 == 0:
print('[Train] Step: %d, loss: %4.5f, acc: %4.5f' % (i+1, loss_val, acc_val))
# 每 5000 次 进行一次 测试
if (i+1) % 5000 == 0:
# 获取数据集,但不随机
test_data = CifarData(test_filename, False)
all_test_acc_val = []
for j in range(test_steps):
test_batch_data, test_batch_labels = test_data.next_batch(batch_size)
test_acc_val = sess.run([accuracy], feed_dict={ x:test_batch_data, y:test_batch_labels })
all_test_acc_val.append(test_acc_val)
test_acc = np.mean(all_test_acc_val)
print('[Test ] Step: %d, acc: %4.5f' % ((i+1), test_acc))
'''
训练一万次的最终结果:
=====================================================
[Train] Step: 10000, loss: 0.75691, acc: 0.75000
[Test ] Step: 10000, acc: 0.74750
=====================================================
'''
其他可以参考:
keras:
ResNet 各个版本 tensorfolw下载:
当然了还有基于keras,TensorLayer,paddlepaddle的实现,当然可以分别基于1.8.4/1.8.5/2.0等版本,可以去github上一探究竟。
二、Pytorch
Pytorch实战2:ResNet-18实现Cifar-10图像分类
实验环境:
- Pytorch 0.4.0
- torchvision 0.2.1
- Python 3.6
- CUDA8+cuDNN v7 (可选)
- Win10+Pycharm
整个项目代码:
ResNet-18网络结构:
ResNet全名Residual Network残差网络。Kaiming He 的《Deep Residual Learning for Image Recognition》获得了CVPR最佳论文。他提出的深度残差网络在2015年可以说是洗刷了图像方面的各大比赛,以绝对优势取得了多个比赛的冠军。而且它在保证网络精度的前提下,将网络的深度达到了152层,后来又进一步加到1000的深度。论文的开篇先是说明了深度网络的好处:特征等级随着网络的加深而变高,网络的表达能力也会大大提高。因此论文中提出了一个问题:是否可以通过叠加网络层数来获得一个更好的网络呢?作者经过实验发现,单纯的把网络叠起来的深层网络的效果反而不如合适层数的较浅的网络效果。因此何恺明等人在普通平原网络的基础上增加了一个shortcut, 构成一个residual block。此时拟合目标就变为F(x),F(x)就是残差:
!
Pytorch上搭建ResNet-18:
'''ResNet-18 Image classfication for cifar-10 with PyTorch
Author 'Sun-qian'.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class ResidualBlock(nn.Module):
def __init__(self, inchannel, outchannel, stride=1):
super(ResidualBlock, self).__init__()
self.left = nn.Sequential(
nn.Conv2d(inchannel, outchannel, kernel_size=3, stride=stride, padding=1, bias=False),
nn.BatchNorm2d(outchannel),
nn.ReLU(inplace=True),
nn.Conv2d(outchannel, outchannel, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(outchannel)
)
self.shortcut = nn.Sequential()
if stride != 1 or inchannel != outchannel:
self.shortcut = nn.Sequential(
nn.Conv2d(inchannel, outchannel, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(outchannel)
)
def forward(self, x):
out = self.left(x)
out += self.shortcut(x)
out = F.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, ResidualBlock, num_classes=10):
super(ResNet, self).__init__()
self.inchannel = 64
self.conv1 = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(64),
nn.ReLU(),
)
self.layer1 = self.make_layer(ResidualBlock, 64, 2, stride=1)
self.layer2 = self.make_layer(ResidualBlock, 128, 2, stride=2)
self.layer3 = self.make_layer(ResidualBlock, 256, 2, stride=2)
self.layer4 = self.make_layer(ResidualBlock, 512, 2, stride=2)
self.fc = nn.Linear(512, num_classes)
def make_layer(self, block, channels, num_blocks, stride):
strides = [stride] + [1] * (num_blocks - 1) #strides=[1,1]
layers = []
for stride in strides:
layers.append(block(self.inchannel, channels, stride))
self.inchannel = channels
return nn.Sequential(*layers)
def forward(self, x):
out = self.conv1(x)
out = self.layer1(out)
out = self.layer2(out)
out = self.layer3(out)
out = self.layer4(out)
out = F.avg_pool2d(out, 4)
out = out.view(out.size(0), -1)
out = self.fc(out)
return out
def ResNet18():
return ResNet(ResidualBlock)
Pytorch上训练:
所选数据集为Cifar-10,该数据集共有60000张带标签的彩色图像,这些图像尺寸32*32,分为10个类,每类6000张图。这里面有50000张用于训练,每个类5000张,另外10000用于测试,每个类1000张。训练时人为修改学习率,当epoch:[1-135] ,lr=0.1;epoch:[136-185], lr=0.01;epoch:[186-240] ,lr=0.001。训练代码如下:
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import argparse
from resnet import ResNet18
# 定义是否使用GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 参数设置,使得我们能够手动输入命令行参数,就是让风格变得和Linux命令行差不多
parser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training')
parser.add_argument('--outf', default='./model/', help='folder to output images and model checkpoints') #输出结果保存路径
parser.add_argument('--net', default='./model/Resnet18.pth', help="path to net (to continue training)") #恢复训练时的模型路径
args = parser.parse_args()
# 超参数设置
EPOCH = 135 #遍历数据集次数
pre_epoch = 0 # 定义已经遍历数据集的次数
BATCH_SIZE = 128 #批处理尺寸(batch_size)
LR = 0.1 #学习率
# 准备数据集并预处理
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4), #先四周填充0,在吧图像随机裁剪成32*32
transforms.RandomHorizontalFlip(), #图像一半的概率翻转,一半的概率不翻转
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), #R,G,B每层的归一化用到的均值和方差
])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train) #训练数据集
trainloader = torch.utils.data.DataLoader(trainset, batch_size=BATCH_SIZE, shuffle=True, num_workers=2) #生成一个个batch进行批训练,组成batch的时候顺序打乱取
testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=100, shuffle=False, num_workers=2)
# Cifar-10的标签
classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
# 模型定义-ResNet
net = ResNet18().to(device)
# 定义损失函数和优化方式
criterion = nn.CrossEntropyLoss() #损失函数为交叉熵,多用于多分类问题
optimizer = optim.SGD(net.parameters(), lr=LR, momentum=0.9, weight_decay=5e-4) #优化方式为mini-batch momentum-SGD,并采用L2正则化(权重衰减)
# 训练
if __name__ == "__main__":
best_acc = 85 #2 初始化best test accuracy
print("Start Training, Resnet-18!") # 定义遍历数据集的次数
with open("acc.txt", "w") as f:
with open("log.txt", "w")as f2:
for epoch in range(pre_epoch, EPOCH):
print('\nEpoch: %d' % (epoch + 1))
net.train()
sum_loss = 0.0
correct = 0.0
total = 0.0
for i, data in enumerate(trainloader, 0):
# 准备数据
length = len(trainloader)
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
# forward + backward
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# 每训练1个batch打印一次loss和准确率
sum_loss += loss.item()
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += predicted.eq(labels.data).cpu().sum()
print('[epoch:%d, iter:%d] Loss: %.03f | Acc: %.3f%% '
% (epoch + 1, (i + 1 + epoch * length), sum_loss / (i + 1), 100. * correct / total))
f2.write('%03d %05d |Loss: %.03f | Acc: %.3f%% '
% (epoch + 1, (i + 1 + epoch * length), sum_loss / (i + 1), 100. * correct / total))
f2.write('\n')
f2.flush()
# 每训练完一个epoch测试一下准确率
print("Waiting Test!")
with torch.no_grad():
correct = 0
total = 0
for data in testloader:
net.eval()
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = net(images)
# 取得分最高的那个类 (outputs.data的索引号)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum()
print('测试分类准确率为:%.3f%%' % (100 * correct / total))
acc = 100. * correct / total
# 将每次测试结果实时写入acc.txt文件中
print('Saving model......')
torch.save(net.state_dict(), '%s/net_%03d.pth' % (args.outf, epoch + 1))
f.write("EPOCH=%03d,Accuracy= %.3f%%" % (epoch + 1, acc))
f.write('\n')
f.flush()
# 记录最佳测试分类准确率并写入best_acc.txt文件中
if acc > best_acc:
f3 = open("best_acc.txt", "w")
f3.write("EPOCH=%d,best_acc= %.3f%%" % (epoch + 1, acc))
f3.close()
best_acc = acc
print("Training Finished, TotalEPOCH=%d" % EPOCH)
实验结果:best_acc= 95.170%