对于模型的保存和加载,下面以最熟悉的实例(mnist手写数字识别)来做实验。
本文主要通过mnist手写数字识别来练习模型的保存和加载,建议了解了手写数字识别再研究这个。
下面共有三个文件:
- train:用于训练数据并保存模型
- test:用于测试数据并加载训练好的模型
- inference:定义一个前向传播的函数
# train.py
import os
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import inference
# 配置神经网络的参数
# 一个训练batch中的训练数据个数,数字越小,越接近随机梯度下降,越大越接近梯度下降
BATCH_SIZE = 100
# 基础的学习率
LEARNING_RATE_BASE = 0.8
# 学习率的衰减率
LEARNING_RATE_DECAY = 0.99
# 描述网络复杂度的正则化向在损失函数中的系数
REGULARIZATION_RATE = 0.0001
# 训练轮数
TRAINING_STEPS = 30000
# 滑动平均衰减率
MOVING_AVERAGE_DECAY = 0.99
# 模型保存的路径
MODEL_SAVE_PATH = "./model"
# 模型保存的文件名
MODEL_NAME = "mnist.ckpt"
def train(mnist):
# 定义输入
x = tf.placeholder(tf.float32, [None, mnist_inference.INPUT_NODE], name='x-input')
# 定义输出
y_ = tf.placeholder(tf.float32, [None, mnist_inference.OUTPUT_NODE], name='y-input')
# 正则化损失
regularizer = tf.contrib.layers.l2_regularizer(REGULARIZATION_RATE)
# 使用mnist_inference的前向传播函数来计算
y = mnist_inference.inference(x, regularizer)
global_step = tf.Variable(0, trainable=False)
# 初始化滑动平均类
variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
# 在所有代表神经网络参数的变量上使用滑动平均,需要被训练的参数,variable_averages
# 返回的就是GraphKeys.TRAINABLE_VARIABLES中的元素
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))
# 计算在当前batch中所有样例的交叉熵平均值
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)
# 使用GradientDescentOptimizer优化损失函数
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')
# 保存模型
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)
_, loss_value, step = sess.run([train_op, loss, global_step],
feed_dict={x: xs, y_: ys})
#每1000轮保存一次模型
if i%1000==0:
# 保存当前图到模型
saver.save(sess, os.path.join(MODEL_SAVE_PATH, MODEL_NAME), global_step=global_step)
def main(argv=None):
# ./data 为数据集存放位置
mnist = input_data.read_data_sets("./data", one_hot=True)
train(mnist)
if __name__=='__main__':
tf.app.run()
# test.py
import time
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#加载mnist_inference和mnist_train中定义的常量和函数
import inference
import train
#每10秒加载一次最新的模型,并在测试数据上测试最新模型的正确率
EVAL_INTERVAL_SECS = 10
def evaluate(mnist):
with tf.Graph().as_default() as g: #将默认图设为g
#定义输入输出的格式
x = tf.placeholder(tf.float32, [None, mnist_inference.INPUT_NODE], name='x-input')
y_ = tf.placeholder(tf.float32, [None, mnist_inference.OUTPUT_NODE], name='y-input')
validate_feed = {x: mnist.validation.images, y_: mnist.validation.labels}
#直接通过调用封装好的函数来计算前向传播的结果
#测试时不关注过拟合问题,所以正则化输入为None
y = mnist_inference.inference(x, None)
#使用前向传播的结果计算正确率,如果需要对未知的样例进行分类
#使用tf.argmax(y, 1)就可以得到输入样例的预测类别
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
# 首先将一个布尔型的数组转换为实数,然后计算平均值
# 平均值就是网络在这一组数据上的正确率
#True为1,False为0
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#通过变量重命名的方式来加载模型
variable_averages = tf.train.ExponentialMovingAverage(mnist_train.MOVING_AVERAGE_DECAY)
variable_to_restore = variable_averages.variables_to_restore()
# 所有滑动平均的值组成的字典,处在/ExponentialMovingAverage下的值
# 为了方便加载时重命名滑动平均量,tf.train.ExponentialMovingAverage类
# 提供了variables_to_store函数来生成tf.train.Saver类所需要的变量
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) #使用此模型检验
#没有初始化滑动平均值,只是调用模型的值,inference只是提供了一个变量的接口,完全没有赋值
print("After %s training steps, validation accuracy = %g"
%(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("./test", one_hot=True)
evaluate(mnist)
if __name__=='__main__':
tf.app.run()
# inference.py
import tensorflow as tf
#输入层的节点数,图片为28*28,为图片的像素
INPUT_NODE = 784
#输出层的节点数,等于类别的数目,需要区分0-9,所以为10类
OUTPUT_NODE = 10
#配置神经网络的参数
#隐藏层的节点数,此神经网络只有一层隐藏层
LAYER1_NODE = 500
#通过tf.get_variable来获取变量,在训练网络时会创建这些变量;在测试时会通过保存的模型加载这些变量
#可以在变量加载的时候对变量重命名,可以通过同样的名字在训练时使用变量自身,而在测试时使用变量的最终值
def get_weight_variable(shape, regularizer):
weights = tf.get_variable("weights", shape,
initializer=tf.truncated_normal_initializer(stddev=0.1))
#当给出正则化函数时,将当前变量的正则化损失加入losses的集合中
#add_to_collection函数讲一个张量加入一个集合
if regularizer != None:
tf.add_to_collection('losses', regularizer(weights))
return weights
#定义神经网络的前向传播过程
def inference(input_tensor, regularizer):
#声明第一层神经网络的变量并完成前向传播过程
with tf.variable_scope("layer1"):
#训练为第一次调用,所以reuse不用设置为True
weights = get_weight_variable([INPUT_NODE, LAYER1_NODE], regularizer)
biases = tf.get_variable("biases", [LAYER1_NODE], initializer=tf.constant_initializer(0.0))
layer1 = tf.nn.relu(tf.matmul(input_tensor, weights)+biases)
#声明第二层神经网络
with tf.variable_scope("layer2"):
weights = get_weight_variable([LAYER1_NODE, OUTPUT_NODE], regularizer)
biases = tf.get_variable("biases", [OUTPUT_NODE], initializer=tf.constant_initializer(0.0))
output = tf.matmul(layer1, weights)+biases
#返回最后前向传播结果
return output
以上便是三个文件的全部代码。
实现该代码时,首先要下载好mnist数据集,然后准备部分数据用来验证。更改代码中的路径,先运行train,然后test即可运行。