复现何凯明Resnet论文正确率0.9+结果,但是正确率还是没有达到0.9以上,因为 101-layers 和 152-layers 的残差块结构和 34-layers 是有一些区别的。
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, is_training):
'''
定义残差块儿
: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 = None,
name = 'conv1'
)
bn = tf.layers.batch_normalization(conv1, training = is_training)
conv1 = tf.nn.relu(bn)
conv2 = tf.layers.conv2d(conv1,
output_channel,
(3, 3),
strides = (1, 1), # 因为 上一层 卷积已经进行过降采样,故这里不需要
padding = 'same',
activation = None,
name = 'conv2'
)
bn = tf.layers.batch_normalization(conv2, training = is_training)
conv2 = tf.nn.relu(bn)
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, is_training):
'''
残差网络主程序
:param