Tensorflow模型保存与读取

import tensorflow as tf
import numpy as np
import os

#输入数据
x_data = np.linspace(-1,1,300)[:, np.newaxis]
noise = np.random.normal(0,0.05, x_data.shape)
y_data = np.square(x_data)-0.5+noise

#输入层
with tf.name_scope('input_layer'): #输入层。将这两个变量放到input_layer作用域下,tensorboard会把他们放在一个图形里面
    xs = tf.placeholder(tf.float32, [None, 1], name = 'x_input') # xs起名x_input,会在图形上显示
    ys = tf.placeholder(tf.float32, [None, 1], name = 'y_input') # ys起名y_input,会在图形上显示

#隐层
with tf.name_scope('hidden_layer'): #隐层。将隐层权重、偏置、净输入放在一起
    with tf.name_scope('weight'): #权重
        W1 = tf.Variable(tf.random_normal([1,10]))
        tf.summary.histogram('hidden_layer/weight', W1)
    with tf.name_scope('bias'): #偏置
        b1 = tf.Variable(tf.zeros([1,10])+0.1)
        tf.summary.histogram('hidden_layer/bias', b1)
    with tf.name_scope('Wx_plus_b'): #净输入
        Wx_plus_b1 = tf.matmul(xs,W1) + b1
        tf.summary.histogram('hidden_layer/Wx_plus_b',Wx_plus_b1)
output1 = tf.nn.relu(Wx_plus_b1)

#输出层
with tf.name_scope('output_layer'): #输出层。将输出层权重、偏置、净输入放在一起
    with tf.name_scope('weight'): #权重
        W2 = tf.Variable(tf.random_normal([10,1]))
        tf.summary.histogram('output_layer/weight', W2)
    with tf.name_scope('bias'): #偏置
        b2 = tf.Variable(tf.zeros([1,1])+0.1)
        tf.summary.histogram('output_layer/bias', b2)
    with tf.name_scope('Wx_plus_b'): #净输入
        Wx_plus_b2 = tf.matmul(output1,W2) + b2
        tf.summary.histogram('output_layer/Wx_plus_b',Wx_plus_b2)
output2 = Wx_plus_b2

#损失
with tf.name_scope('loss'): #损失
    loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-output2),reduction_indices=[1]))
    tf.summary.scalar('loss',loss)
with tf.name_scope('train'): #训练过程
    train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

#模型保存加载工具
saver = tf.train.Saver()

#判断模型保存路径是否存在,不存在就创建
sess = tf.Session()
if not os.path.exists('tmp/'):
    os.mkdir('tmp/')

if os.path.exists('tmp/checkpoint'): #判断模型是否存在
    saver.restore(sess, 'tmp/model.ckpt') #存在就从模型中恢复变量
else:
    init = tf.global_variables_initializer() #不存在就初始化变量
    sess.run(init)

#可视化
merged = tf.summary.merge_all() #将图形、训练过程等数据合并在一起
writer = tf.summary.FileWriter('logs',sess.graph) #将训练日志写入到logs文件夹下

#训练
for i in range(1000):
    _,loss_value = sess.run([train_step,loss],feed_dict={xs:x_data,ys:y_data})
    if(i%50==0): #每50次写一次日志
    	save_path = saver.save(sess, 'tmp/model.ckpt') #保存模型到tmp/model.ckpt,注意一定要有一层文件夹,否则保存不成功!!!
    	result = sess.run(merged,feed_dict={xs:x_data,ys:y_data}) #计算需要写入的日志数据
    	print("模型保存:%s 当前训练损失:%s"%(save_path, loss_value))
    	writer.add_summary(result,i) #将日志数据写入文件

模型结构如下:

Tensorflow模型保存与读取

 

训练结果如下:

本次训练:

模型保存:tmp/model.ckpt 当前训练损失:0.6274387
模型保存:tmp/model.ckpt 当前训练损失:0.020334238
模型保存:tmp/model.ckpt 当前训练损失:0.010965167
模型保存:tmp/model.ckpt 当前训练损失:0.010010023
模型保存:tmp/model.ckpt 当前训练损失:0.00977526
模型保存:tmp/model.ckpt 当前训练损失:0.009599457
模型保存:tmp/model.ckpt 当前训练损失:0.009416369
模型保存:tmp/model.ckpt 当前训练损失:0.009232028
模型保存:tmp/model.ckpt 当前训练损失:0.009042832
模型保存:tmp/model.ckpt 当前训练损失:0.008852347
模型保存:tmp/model.ckpt 当前训练损失:0.008678828
模型保存:tmp/model.ckpt 当前训练损失:0.008507592
模型保存:tmp/model.ckpt 当前训练损失:0.008340045
模型保存:tmp/model.ckpt 当前训练损失:0.008179325
模型保存:tmp/model.ckpt 当前训练损失:0.0080236485
模型保存:tmp/model.ckpt 当前训练损失:0.007861079
模型保存:tmp/model.ckpt 当前训练损失:0.007693918
模型保存:tmp/model.ckpt 当前训练损失:0.0075272443
模型保存:tmp/model.ckpt 当前训练损失:0.0073627653
模型保存:tmp/model.ckpt 当前训练损失:0.0071906

 

下一次训练:

模型保存:tmp/model.ckpt 当前训练损失:0.0060096276
模型保存:tmp/model.ckpt 当前训练损失:0.005623365
模型保存:tmp/model.ckpt 当前训练损失:0.005464178
模型保存:tmp/model.ckpt 当前训练损失:0.0053191767
模型保存:tmp/model.ckpt 当前训练损失:0.005191032
模型保存:tmp/model.ckpt 当前训练损失:0.0050708964
模型保存:tmp/model.ckpt 当前训练损失:0.00495239
模型保存:tmp/model.ckpt 当前训练损失:0.0048394804
模型保存:tmp/model.ckpt 当前训练损失:0.004734584
模型保存:tmp/model.ckpt 当前训练损失:0.004636375
模型保存:tmp/model.ckpt 当前训练损失:0.0045456053
模型保存:tmp/model.ckpt 当前训练损失:0.00446251
模型保存:tmp/model.ckpt 当前训练损失:0.004385399
模型保存:tmp/model.ckpt 当前训练损失:0.004307924
模型保存:tmp/model.ckpt 当前训练损失:0.004229113
模型保存:tmp/model.ckpt 当前训练损失:0.004153334
模型保存:tmp/model.ckpt 当前训练损失:0.0040837238
模型保存:tmp/model.ckpt 当前训练损失:0.004026236
模型保存:tmp/model.ckpt 当前训练损失:0.0039764466
模型保存:tmp/model.ckpt 当前训练损失:0.0039317617

 

可见:下次训练是接着上次训练继续的。因此可以将训练模型保存下来,下次继续训练。