您的位置:首页 > 其它

TensorFlow官方文档中文版-笔记(六)

2017-11-02 22:10 337 查看

复杂的CNN(加入trick)

为与中文文档同步做个笔记,没细研究。

完整代码如下:

# TensorFlow进阶-实现进阶的CNN
from CNN import cifar10, cifar10_input
import math
import tensorflow as tf
import numpy as np
import time

max_steps = 3000
batch_size = 128
data_dir = 'cifar-10-batches-py/'

def variable_with_weight_loss(shape, stddev, w1):
var = tf.Variable(tf.truncated_normal(shape, stddev=stddev))
if w1 is not None:
# 使用w1控制L2 loss的大小,使用tf.nn.l2_loss计算weight的L2 loss,再使用tf.multiply让L2 loss乘以w1,得到最后的weight loss.
weight_loss = tf.multiply(tf.nn.l2_loss(var), w1, name='weight_loss')
# 使用add_to_collection把weight loss统一存到一个collection,在后面计算神经网络总体loss时被用上
tf.add_to_collection('losses', weight_loss)
return var

# 产生训练需要使用的数据,包括特征及其对应的label,每次执行时都会生成一个batch_size的数量的样本。(对数据进行了数据增强,Data Augmentation)
# distorted_inputs需要耗费大量CPU时间,因因此它使用了16个独立的线程来加速任务,函数内部会产生线程池,在需要使用时会通过TensorFlow queue进行调度
images_train, labels_train = cifar10_input.distorted_inputs(data_dir=data_dir, batch_size=batch_size)
# 产生测试数据
images_test, labels_test = cifar10_input.inputs(eval_data=True, data_dir=data_dir, batch_size=batch_size)

# 特征,batch_size在之后定义网络结构时被用到,故数据尺寸中的第一个值即样本条数需要被预先设定,不能再设置为None
# 图片尺寸为24*24,即裁剪后的大小;颜色通道数设为3,代表图片是彩色有RGB三条通道
image_holder = tf.placeholder(tf.float32, [batch_size, 24, 24, 3])
label_holder = tf.placeholder(tf.int32, [batch_size])

# 第一个卷积层使用5*5的卷积核大小,3个颜色通道,64个卷积核,weight初始化函数的标准差为0.05,不对第一个卷积层的weight进行L2正则,因此w1设为0
weight1 = variable_with_weight_loss(shape=[5, 5, 3, 64], stddev=5e-2, w1=0.0)
# 对输入数据image_holder进行卷积操作
kernel1 = tf.nn.conv2d(image_holder, weight1, [1, 1, 1, 1], padding='SAME')
bias1 = tf.Variable(tf.constant(0.0, shape=[64]))
conv1 = tf.nn.relu(tf.nn.bias_add(kernel1, bias1))
# 使用尺寸3*3且步长为2*2的最大池化层处理数据
pool1 = tf.nn.max_pool(conv1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME')
# LRN对结果进行处理
# LRN层模仿了生物神经系统的"侧抑制"机制,对局部神经元的活动创建竞争环境,使得其中响应比较大的值变得相对更大,并抑制其他反馈较小的神经元,增强了模型的泛化能力
# LRN对RELU这种没有上限边界的激活函数比较有用,因为它会从附近的多个卷积核的响应中挑选比较大的反馈,但不适合sigmod这种有固定边界且能抑制过大值得激活函数
norm1 = tf.nn.lrn(pool1, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75)

# 第二个卷积层,与第一个略微不同
# 3->64
weight2 = variable_with_weight_loss(shape=[5, 5, 64, 64], stddev=5e-2, w1=0.0)
kernel2 = tf.nn.conv2d(image_holder, weight1, [1, 1, 1, 1], padding='SAME')
# 0.0->0.1
bias2 = tf.Variable(tf.constant(0.1, shape=[64]))
conv2 = tf.nn.relu(tf.nn.bias_add(kernel1, bias1))
# norm层、pool层顺序调换
norm2 = tf.nn.lrn(pool1, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75)
pool2 = tf.nn.max_pool(conv1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME')

# 两个卷积层后,使用一个全连接层
# 把第二个卷积层的输出结果flatten,将每个样本变成一维向量
reshape = tf.reshape(pool2, [batch_size, -1])
# 获取数据扁平化后的长度
dim = reshape.get_shape()[1].value
# 对全连接层weight进行初始化,隐含节点数384
# 需要这个全连接层不要过拟合,因此设了一个非零的weight loss值0.004,让这层所有参数都被L2正则所约束
weight3 = variable_with_weight_loss(shape=[dim, 384], stddev=0.04, w1=0.004)
bias3 = tf.Variable(tf.constant(0.1, shape=[384]))
local3 = tf.nn.relu(tf.matmul(reshape, weight3) + bias3)

# 这个全连接层与前一层很像,只是隐含节点数下降了一半,只有192个,其他超参数不变
weight4 = variable_with_weight_loss(shape=[384, 192], stddev=0.04, w1=0.004)
bias4 = tf.Variable(tf.constant(0.1, shape=[192]))
local4 = tf.nn.relu(tf.matmul(local3, weight4) + bias4)

# 最后一层,与之前使用softmax输出最后结果不同,这里把softmax的操作放在了计算loss的部分
weight5 = variable_with_weight_loss(shape=[192, 10], stddev=1 / 192.0, w1=0.0)
bias5 = tf.Variable(tf.constant(0.0, shape=[10]))
logits = tf.add(tf.matmul(local4, weight5), bias5)

# conv1 卷积层和RELU激活函数
# pool1 最大池化
# norm1 LRN
# conv2 卷积层和RELU激活函数
# norm2 LRN
# pool2 最大池化
# local3 全连接层和RELU激活函数
# local4 全连接层和RELU激活函数
# logits 模型inference的输出结果

# 以上为模型inference部分的构建,接下来计算CNN的loss

def loss(logits, labels):
labels = tf.cast(labels, tf.int64)
# 把softmax的计算和cross entropy loss的计算合在一起
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels,
name='cross_entropy_per_example')
cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy')
tf.add_to_collection('losses', cross_entropy_mean)
return tf.add_n(tf.get_collection('losses'), name='total_loss')

# 将logits节点和label_holder传入loss函数获得最终的loss
loss = loss(logits, label_holder)
train_op = tf.train.AdamOptimizer(1e-3).minimize(loss)
# 求输出结果top k的准确率,默认top 1,即输出分数最高的那一类的准确率
top_k_op = tf.nn.in_top_k(logits, label_holder, 1)

sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

# 启动线程(必须的操作,否则后续inference及训练无法开始)
tf.train.start_queue_runners()

# 开始训练
for step in range(max_steps):
start_time = time.time()
# 先使用session的run方法执行images_train, labels_train的计算,获得一个batch的训练数据
image_batch, label_batch = sess.run([images_train, labels_train])
_, loss_value = sess.run([train_op, loss], feed_dict={image_holder: image_batch, label_holder: label_batch})
duration = time.time() - start_time
if step % 10 == 0:
examples_per_sec = batch_size / duration
sec_per_batch = float(duration)

print('step %d,loss=%.2f (%.1f examples/sec; %.3f sec/batch)' % (
step, loss_value, examples_per_sec, sec_per_batch))

# 评测在测试集上的准确率
num_examples = 10000
num_iter = int(math.ceil(num_examples / batch_size))
true_count = 0
total_sample_count = num_iter * batch_size
step = 0
while step < num_iter:
image_batch, label_batch = sess.run([images_test, labels_test])
predictions = sess.run([top_k_op], feed_dict={image_holder: image_batch, label_holder: label_batch})
true_count += np.sum(predictions)
step += 1

precision = true_count / total_sample_count
print('precision @ 1 = %.3f' % precision)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: