由于神经网络训练比较复杂所以可能需要先保存训练好的模型,然后再需要的时候进行调用,下面介绍两种保存模型的方法:
方法一:使用tf.train.Saver()
保存代码,该方法保存的模型比较全,只要定义的变量均可获取,导入的模型与当前生成几乎具有一样的能力:
#定义占位符,具有名称的变量可以被在导入模型后获取
x = tf.placeholder(tf.float32, [None, 784], name ='x')
y_ = tf.placeholder(tf.int64, [None], name='y_')
#有些变量名难以定义,可以通过下面的方法保存
tf.add_to_collection('pred_network', y_conv)
tf.add_to_collection('pred_network', keep_prob)
#保存模型,目录model,前缀mnist_model
saver = tf.train.Saver()
with tf.Session() as sess:
#训练部分,省略
saver.save(sess, './model/mist_model')
加载:
with tf.Session() as sess:
model = tf.train.import_meta_graph('./model/mist_model.meta')
model.restore(sess, './model/mist_model')
#加载变量,注意变量名必须是定义过的:
#这部分因为是将变量存入一个集合中,所以需要注意顺序
y_conv = tf.get_collection('pred_network')[0]
keep_prob = tf.get_collection('pred_network')[1]
graph = tf.get_default_graph()
x = graph.get_operation_by_name('x').outputs[