此例程出自《TensorFlow實戰Google深度學習框架》6.4.1小節 經典卷積網絡模型之LeNet-5模型,具體可搜索“LeNet-5, convolutional neural networks”。
例程中的網絡模型與原始LeNet-5模型不太一樣,網絡結構如下:
INPUT: [28x28x1] weights: 0
CONV5-32: [28x28x32] weights: (5*5*1+1)*32
POOL2: [14x14x32] weights: 0
CONV5-64: [14x14x64] weights: (5*5*32+1)*64
POOL2: [7x7x64] weights: 0
FC: [1x1x512] weights: (7*7*64+1)*512
FC: [1x1x10] weights: (1*1*512+1)*10
工程目錄:
-mnist_lenet5
-dataset //存放數據集的文件夾,可以http://yann.lecun.com/exdb/mnist/下載
-model //存放模型的文件夾
-mnist_eval.py //定義了測試過程
-mnist_inference.py //定義了前向傳播的過程以及神經網絡中的參數
-mnist_train.py //定義了神經網絡的訓練過程
這個和上一篇《TensorFlow最佳實踐樣例程序》程序是一致的,改動大部分集中在mnist_inference.py前向傳播過程。
代碼實現
mnist_eval.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 加載mnist_inference.py 和 mnist_train.py中定義的常量和函數
import mnist_inference
import mnist_train
# 每10秒加載一次最新的模型, 並在測試數據上測試最新模型的正確率
EVAL_INTERVAL_SECS = 10
def evaluate(mnist):
with tf.Graph().as_default() as g:
# 定義輸入輸出的格式
x = tf.placeholder(tf.float32, [
mnist.validation.num_examples, # 第一維表示樣例的個數
mnist_inference.IMAGE_SIZE, # 第二維和第三維表示圖片的尺寸
mnist_inference.IMAGE_SIZE,
mnist_inference.NUM_CHANNELS], # 第四維表示圖片的深度,對於RBG格式的圖片,深度爲5
name='x-input')
y_ = tf.placeholder(tf.float32, [None, mnist_inference.OUTPUT_NODE], name='y-input')
validate_feed = {x: np.reshape(mnist.validation.images, (mnist.validation.num_examples, mnist_inference.IMAGE_SIZE, mnist_inference.IMAGE_SIZE, mnist_inference.NUM_CHANNELS)),
y_: mnist.validation.labels}
# 直接通過調用封裝好的函數來計算前向傳播的結果。
# 因爲測試時不關注正則損失的值,所以這裏用於計算正則化損失的函數被設置爲None。
y = mnist_inference.inference(x, False, None)
# 使用前向傳播的結果計算正確率。
# 如果需要對未知的樣例進行分類,那麼使用tf.argmax(y, 1)就可以得到輸入樣例的預測類別了。
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# 通過變量重命名的方式來加載模型,這樣在前向傳播的過程中就不需要調用求滑動平均的函數來獲取平局值了。
# 這樣就可以完全共用mnist_inference.py中定義的前向傳播過程
variable_averages = tf.train.ExponentialMovingAverage(mnist_train.MOVING_AVERAGE_DECAY)
variable_to_restore = variable_averages.variables_to_restore()
saver = tf.train.Saver(variable_to_restore)
#每隔EVAL_INTERVAL_SECS秒調用一次計算正確率的過程以檢測訓練過程中正確率的變化
while True:
with tf.Session() as sess:
# tf.train.get_checkpoint_state函數會通過checkpoint文件自動找到目錄中最新模型的文件名
ckpt = tf.train.get_checkpoint_state(mnist_train.MODEL_SAVE_PATH)
if ckpt and ckpt.model_checkpoint_path:
# 加載模型
saver.restore(sess, ckpt.model_checkpoint_path)
# 通過文件名得到模型保存時迭代的輪數
global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
accuracy_score = sess.run(accuracy, feed_dict = validate_feed)
print("After %s training step(s), validation accuracy = %f" % (global_step, accuracy_score))
else:
print("No checkpoint file found")
return
time.sleep(EVAL_INTERVAL_SECS)
def main(argv=None):
mnist = input_data.read_data_sets("dataset/", one_hot=True)
evaluate(mnist)
if __name__ == '__main__':
tf.app.run()
mnist_inference.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tensorflow as tf
# 定義神經網絡相關的參數
INPUT_NODE = 784
OUTPUT_NODE = 10
LAYER1_NODE = 500
IMAGE_SIZE = 28
NUM_CHANNELS = 1
NUM_LABELS = 10
# 第一層卷積層的尺寸和深度
CONV1_DEEP = 32
CONV1_SIZE = 5
# 第二層卷積層的尺寸和深度
CONV2_DEEP = 64
CONV2_SIZE = 5
# 全連接層的節點個數
FC_SIZE = 512
# 定義神經網絡的前向傳播過程。
# 這裏添加了一個新的參數train,用於區別訓練過程和測試過程。
# 在這個程序中將用到dropout方法,dropout可以進一步提升模型可靠性並防止過擬合,dropout過程只在訓練時使用。
def inference(input_tensor, train, regularizer):
# 聲明第一層神經網絡的變量並完成前向傳播過程。這個過程和6.3.1小節中介紹的一致。
# 通過使用不同的命名空間來隔離不同層的變量,這可以讓每一層中的變量命名只需要考慮在當前層的作用,而不需要擔心重名的問題。
# 和標準LeNet-5模型不大一樣,這裏定義卷積層的輸入爲28*28*1的原始MNIST圖片像素。
# 因爲卷積層中使用了全0填充,所以輸出爲28*28*32的矩陣。
with tf.variable_scope('layer1-conv1'):
# 這裏使用tf.get_variable或tf.Variable沒有本質區別,因爲在訓練或是測試中沒有在同一個程序中多次調用這個函數。
# 如果在同一個程序中多次調用,在第一次調用之後需要將reuse參數置爲True。
conv1_weights = tf.get_variable(
"weight", [CONV1_SIZE, CONV1_SIZE, NUM_CHANNELS, CONV1_DEEP],
initializer = tf.truncated_normal_initializer(stddev=0.1)
)
conv1_biases = tf.get_variable("bias", [CONV1_DEEP], initializer=tf.constant_initializer(0.0))
# 使用邊長爲5,深度爲32的過濾器,過濾器移動的步長爲1,且使用全0填充
conv1 = tf.nn.conv2d(input_tensor, conv1_weights, strides=[1, 1, 1, 1], padding='SAME')
relu1 = tf.nn.relu(tf.nn.bias_add(conv1, conv1_biases))
# 實現第二層池化層的前向傳播過程。
# 這裏選用最大池化層,池化層過濾器的邊長爲2,使用全0填充且移動的步長爲2。
# 這一層的輸入是上一層的輸出,也就是28*28*32的矩陣。輸出爲14*14*32的矩陣。
with tf.name_scope('layer2-pool'):
pool1 = tf.nn.max_pool(relu1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# 聲明第三層卷積層的變量並實現前向傳播過程。
# 這一層的輸入爲14*14*32的矩陣,輸出爲14*14*64的矩陣。
with tf.variable_scope('layer3-conv2'):
conv2_weights = tf.get_variable(
"weight", [CONV2_SIZE, CONV2_SIZE, CONV1_DEEP, CONV2_DEEP],
initializer = tf.truncated_normal_initializer(stddev=0.1)
)
conv2_biases = tf.get_variable("bias", [CONV2_DEEP], initializer=tf.constant_initializer(0.0))
# 使用邊長爲5,深度爲64的過濾器,過濾器移動的步長爲1,且使用全0填充
conv2 = tf.nn.conv2d(pool1, conv2_weights, strides=[1, 1, 1, 1], padding='SAME')
relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2_biases))
# 實現第四層池化層的前向傳播過程。
# 這一層和第二層的結構是一樣的。這一層的輸入爲14*14*64的矩陣,輸出爲7*7*64的矩陣。
with tf.name_scope('layer4-poo2'):
pool2 = tf.nn.max_pool(relu2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# 將第四層池化層的輸出轉化爲第五層全連接層的輸入格式。
# 第四層的輸出爲7*7*64的矩陣,然而第五層全連接層需要的輸入格式爲向量,所以在這裏需要將這個7*7*64的矩陣拉直成一個向量。
# pool2.get_shape函數可以得到第四層輸出矩陣的維度而不需要手工計算。
# 注意因爲每一層神經網絡的輸入輸出都爲一個batch的矩陣,所以這裏得到的維度也包含了一個batch中數據的個數。
pool_shape = pool2.get_shape().as_list()
# 計算將矩陣拉直成向量之後的長度,這個長度就是矩陣長度及深度的乘積。
# 注意這裏pool_shape[0]爲一個batch中樣本的個數。
nodes = pool_shape[1] * pool_shape[2] * pool_shape[3]
# 通過tf.reshape函數將第四層的輸出變成一個batch的向量。
reshaped = tf.reshape(pool2, [pool_shape[0], nodes])
# 聲明第五層全連接層的變量並實現前向傳播過程。
# 這一層的輸入是拉直之後的一組向量,向量長度爲7*7*64=3136,輸出是一組長度爲512的向量。
# 這一層和之前在第5章中介紹的基本一致,唯一的區別是引入了dropout的概念。
# dropout在訓練時會隨機將部分節點的輸出改爲0。
# dropout可以避免過擬合問題,從而使得模型在測試數據上的效果更好。
# dropout一般只在全連接層而不是卷積層或者池化層使用。
with tf.variable_scope('layer5-fc1'):
fc1_weights = tf.get_variable("weight", [nodes, FC_SIZE],
initializer = tf.truncated_normal_initializer(stddev = 0.1))
# 只有全連接層的權重需要加入正則化
if regularizer != None:
tf.add_to_collection('losses', regularizer(fc1_weights))
fc1_biases = tf.get_variable('bias', [FC_SIZE], initializer = tf.constant_initializer(0.1))
fc1 = tf.nn.relu(tf.matmul(reshaped, fc1_weights)+fc1_biases)
if train:
fc1 = tf.nn.dropout(fc1, 0.5)
# 聲明第六層全連接層的變量並實現前向傳播過程。
# 這一層的輸入是一組長度爲512的向量,輸出是一組長度爲10的向量。
# 這一層的輸出通過Softmax之後就得到了最後的分類結果。
with tf.variable_scope('layer6-fc2'):
fc2_weights = tf.get_variable("weight", [FC_SIZE, NUM_LABELS],
initializer = tf.truncated_normal_initializer(stddev = 0.1))
if regularizer != None:
tf.add_to_collection('losses', regularizer(fc2_weights))
fc2_biases = tf.get_variable('bias', [NUM_LABELS], initializer = tf.constant_initializer(0.1))
logit = tf.matmul(fc1, fc2_weights) + fc2_biases
# 返回第六層的輸出
return logit
mmnist_train.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 加載mnist_inference.py中定義的常量和前向傳播的函數
import mnist_inference
# 配置神經網絡的參數
BATCH_SIZE = 100
LEARNING_RATE_BASE = 0.01
LEARNING_RATE_DECAY = 0.99
REGULARAZTION_RATE = 0.0001
TRAINING_STEPS = 30000
MOVING_AVERAGE_DECAY = 0.99
# 模型保存的路徑和文件名
MODEL_SAVE_PATH = "model/"
MODEL_NAME = "model.ckpt"
def train(mnist):
# 定義輸入輸出placeholder
# 調整輸入數據placeholder的格式,輸入爲一個四維矩陣
x = tf.placeholder(tf.float32, [
BATCH_SIZE, # 第一維表示一個batch中樣例的個數
mnist_inference.IMAGE_SIZE, # 第二維和第三維表示圖片的尺寸
mnist_inference.IMAGE_SIZE,
mnist_inference.NUM_CHANNELS], # 第四維表示圖片的深度,對於RBG格式的圖片,深度爲5
name='x-input')
y_ = tf.placeholder(tf.float32, [None, mnist_inference.OUTPUT_NODE], name='y-input')
regularizer = tf.contrib.layers.l2_regularizer(REGULARAZTION_RATE)
# 直接使用mnist_inference.py中定義的前向傳播過程
y = mnist_inference.inference(x, True, regularizer)
global_step = tf.Variable(0, trainable=False)
#定義損失函數、學習率、滑動平均操作以及訓練過程
variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
variable_averages_op = variable_averages.apply(tf.trainable_variables())
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=tf.argmax(y_, 1))
cross_entropy_mean = tf.reduce_mean(cross_entropy)
loss = cross_entropy_mean + tf.add_n(tf.get_collection('losses'))
learning_rate = tf.train.exponential_decay(LEARNING_RATE_BASE, global_step, mnist.train.num_examples/BATCH_SIZE, LEARNING_RATE_DECAY)
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
with tf.control_dependencies([train_step, variable_averages_op]):
train_op = tf.no_op(name='train')
# 初始化Tensorflow持久化類
saver = tf.train.Saver()
with tf.Session() as sess:
tf.global_variables_initializer().run()
# 驗證和測試的過程將會有一個獨立的程序來完成
for i in range(TRAINING_STEPS):
xs, ys = mnist.train.next_batch(BATCH_SIZE)
#類似地將輸入的訓練數據格式調整爲一個四維矩陣,並將這個調整後的數據傳入sess.run過程
reshaped_xs = np.reshape(xs, (BATCH_SIZE, mnist_inference.IMAGE_SIZE, mnist_inference.IMAGE_SIZE, mnist_inference.NUM_CHANNELS))
_, loss_value, step = sess.run([train_op, loss, global_step], feed_dict={x: reshaped_xs, y_: ys})
#每1000輪保存一次模型。
if i%1000 == 0:
# 輸出當前的訓練情況。這裏只輸出了模型在當前訓練batch上的損失函數大小。通過損失函數的大小可以大概瞭解訓練的情況。
# 在驗證數據集上的正確率信息會有一個單獨的程序來生成。
print("After %d training step(s), loss on training batch is %f." % (step, loss_value))
# 保存當前的模型。注意這裏隔出了global_step參數,這樣可以讓每個被保存模型的文件名末尾加上訓練的輪數,比如“model.ckpt-1000”表示訓練1000輪後得到的模型
saver.save(sess, os.path.join(MODEL_SAVE_PATH, MODEL_NAME), global_step=global_step)
def main(argv=None):
mnist = input_data.read_data_sets("dataset/", one_hot=True)
train(mnist)
if __name__ == '__main__':
tf.app.run()
實驗及分析
- 由於是在上一個程序TensorFlow最佳實踐樣例程序 修改的,剛開始只是使用了它的學習率
LEARNING_RATE_BASE = 0.8
。
訓練過程:
測試結果:
可以明顯看出不收斂,準確率跟瞎猜差不多。 - 對上述結果分析原因:可能學習率太高。將其改爲0.01。
訓練過程:
測試結果:
準確率99.04%,符合預期。