背景
学习Tensorflow的代码,加强工程应用能力,本篇文章将对CIFAR10数据集利用简单的CNN模型进行分类,对代码进行整理和分析理解。
CIFAR10数据集
CIFAR-10数据集,包含有60000张32x32彩色图像,10个不同类别,每个类别包含6000张图像。训练图像50000张,测试图像10000张。详见http://www.cs.toronto.edu/~kriz/cifar.html
代码学习及分析
1.加载cifer10数据
'''1.加载数据集'''
(x,y), (x_test, y_test) = datasets.cifar10.load_data() #下载cifar10数据集,自动下载,返回ndarray
y = tf.squeeze(y, axis=1) #返回一个tensor,这个tensor的每个维度都不为1
y_test = tf.squeeze(y_test, axis=1)
print(x.shape, y.shape, x_test.shape, y_test.shape)
#x是(50000,32,32,3)表示5w张32x32x3的图像,y是(50000,)x_test是(10000,32,32,3)y_test是(10000,),
'''训练集'''
train_db = tf.data.Dataset.from_tensor_slices((x,y))
train_db = train_db.shuffle(1000).map(preprocess).batch(128)#随机打散、预处理、批处理
'''测试集'''
test_db = tf.data.Dataset.from_tensor_slices((x_test,y_test))
test_db = test_db.map(preprocess).batch(64)
sample = next(iter(train_db)) #从训练集中采样一个 Batch,并观察
print('sample:', sample[0].shape, sample[1].shape,
tf.reduce_min(sample[0]), tf.reduce_max(sample[0]))
在这个代码中,from_tensor_slices
的作用是把给定的元组、列表和张量等数据进行特征切片,将图片x和标签y转换为数据集对象,train_db的shape和type如下图,另外,参数的数据集对象,一般都要经过一些数据处理,例如预处理、随机打散、按批装载等,接下来会提到这些函数
train_db.shuffle(1000)
的作用是随机打散,防止按顺序的产生,出现记忆
map(preprocess)
是一个映射函数,也就是将上一步的结果(随机打散后的数据集)进行preprocess处理,具体方法由自己实现,这里使用下列代码,也就是归一化操作
def preprocess(x, y):
# [0~1]
x = 2*tf.cast(x, dtype=tf.float32) / 255.-1
y = tf.cast(y, dtype=tf.int32)
return x,y
batch(128)
是设之数据集为批训练模式,也就是每128个数据喂入网络进行训练,这个大小得按照自己处理器的性能来决定。当然,batch_size的选择是有要求的,越大,训练时间越大,内存容量也受不了,或会导致梯度下降方向不再改变;越小,不收敛,精度低。因此得适中。
2.构建网络模型
这里使用VGG13作为网络模型,如下图所示。
首先是卷积网络部分,包含有5个单元,每个单元都是2个卷积层+1个池化层:
conv_layers = [ # 5 units of conv + max pooling
# unit 1
layers.Conv2D(64, kernel_size=[3, 3], padding="same", activation=tf.nn.relu),
layers.Conv2D(64, kernel_size=[3, 3], padding="same", activation=tf.nn.relu),
layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'),
# unit 2
layers.Conv2D(128, kernel_size=[3, 3], padding="same", activation=tf.nn.relu),
layers.Conv2D(128, kernel_size=[3, 3], padding="same", activation=tf.nn.relu),
layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'),
# unit 3
layers.Conv2D(256, kernel_size=[3, 3], padding="same", activation=tf.nn.relu),
layers.Conv2D(256, kernel_size=[3, 3], padding="same", activation=tf.nn.relu),
layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'),
# unit 4
layers.Conv2D(512, kernel_size=[3, 3], padding="same", activation=tf.nn.relu),
layers.Conv2D(512, kernel_size=[3, 3], padding="same", activation=tf.nn.relu),
layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'),
# unit 5
layers.Conv2D(512, kernel_size=[3, 3], padding="same", activation=tf.nn.relu),
layers.Conv2D(512, kernel_size=[3, 3], padding="same", activation=tf.nn.relu),
layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'
]
conv_net = Sequential(conv_layers)
然后是全连接网络部分,3个全连接层,使用的ReLU作为激活函数:
fc_net = Sequential([
layers.Dense(256, activation=tf.nn.relu),
layers.Dense(128, activation=tf.nn.relu),
layers.Dense(10, activation=None),
])
然后是对其进行build,利用summary函数就可以打印网络参数
conv_net.build(input_shape=[None, 32, 32, 3])
fc_net.build(input_shape=[None, 512])
conv_net.summary()
fc_net.summary()
3.训练网络
optimizer = optimizers.Adam(lr=1e-4)
# [1, 2] + [3, 4] => [1, 2, 3, 4]
variables = conv_net.trainable_variables + fc_net.trainable_variables
for epoch in range(50):
for step, (x,y) in enumerate(train_db):
with tf.GradientTape() as tape:
# [b, 32, 32, 3] => [b, 1, 1, 512]
out = conv_net(x)
# flatten, => [b, 512]
out = tf.reshape(out, [-1, 512])
# [b, 512] => [b, 10]
logits = fc_net(out)
# [b] => [b, 10]
y_onehot = tf.one_hot(y, depth=10)
# compute loss
# loss = tf.losses.categorical_crossentropy(y_onehot, logits, from_logits=True)#tf2.0
loss = tf.keras.backend.categorical_crossentropy(y_onehot, logits, from_logits=True)
loss = tf.reduce_mean(loss)
grads = tape.gradient(loss, variables)
optimizer.apply_gradients(zip(grads, variables))
if step %100 == 0:
# print(epoch,step,'loss',float(loss)) # tf2.0
print(epoch, step, 'loss:', loss)
total_num = 0
total_correct = 0
for x,y in test_db:
out = conv_net(x)
out = tf.reshape(out, [-1, 512])
logits = fc_net(out)
prob = tf.nn.softmax(logits, axis=1)
pred = tf.argmax(prob, axis=1) #得到得分值最大那个的序号
pred = tf.cast(pred, dtype=tf.int32)
correct = tf.cast(tf.equal(pred, y), dtype=tf.int32)
correct = tf.reduce_sum(correct)
total_num += x.shape[0]
total_correct += int(correct)
acc = total_correct / total_num
print(epoch, 'acc:', acc)
optimizer
选用Adam,参数1e-4,优化器是用来辅助梯度下降的。
variables = conv_net.trainable_variables + fc_net.trainable_variables
表示将两个网络给合并在一起,最后形成VGG13
grads = tape.gradient(loss, variables);optimizer.apply_gradients(zip(grads, variables))
中,loss选用交叉熵损失函数,对网络进行梯度求解,应用到apply_gradients方法,进行梯度下降。
one-hot()
是对标签进行one-hot编码,比如y分为0~9,10个分类,那么类别4,0001000000。目的是为了方便进行损失计算。
acc
的计算方式就理解起来就比较容易了,对测试集中每一个数据,进行计算,放到网络中,出来的结果是啥,跟真实标签匹配不,匹配就加1,最后得到匹配结果的数目的比例
参考代码
https://github.com/dragen1860/Deep-Learning-with-TensorFlow-book/tree/master/ch10
相关参考资料
1.from_tensor_slices
的作用
2.深度学习中batch_size大小选择的影响
3.Adam算法
4.交叉熵损失函数
[其它自查]