tensorflow复习日记(八)保存模型

发现一个问题,原来的代码在同一个文件中保存,读取模型是没有问题的,但是不同文件就不行。
原来是保存分2种,ckpt和pb模式。
ckpt中也保存了图的结构,所以正确用法应该是训练模型中把要使用的变量都起个名字。
然后读取后把这些名字读取出来,作为输入,输出,然后喂数据,进行预测:
保存部分代码:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#mnist已经作为官方的例子,做好了数据下载,分割,转浮点等一系列工作,源码在tensorflow源码中都可以找到
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

# 配置每个 GPU 上占用的内存的比例
# 没有GPU直接sess = tf.Session()
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.95)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))

#每个批次的大小
batch_size = 20
#定义训练轮数据
train_epoch = 1
#定义每n轮输出一次
test_epoch_n = 1

#计算一共有多少批次
n_batch = mnist.train.num_examples // batch_size
print("batch_size="+str(batch_size)+"n_batch="+str(n_batch))

#占位符,定义了输入,输出
x = tf.placeholder(tf.float32,[None, 784],name='InputFeature') 
y_ = tf.placeholder(tf.float32,[None, 10],name='InputLabel') 
#权重和偏置,使用0初始化
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))

#这里定义的网络结构
y = tf.nn.softmax(tf.matmul(x,W) + b,name='NetOutput') 
#损失函数是交叉熵
#cross_entropy = -tf.reduce_sum(y_*tf.log(y))
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_,logits=y))
#训练方法:
#train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
train_step = tf.train.AdamOptimizer(1e-2).minimize(cross_entropy)
#初始化sess中所有变量
init = tf.global_variables_initializer() 
sess.run(init) 

MaxACC = 0#最好的ACC
saver = tf.train.Saver()  

#训练n个epoch
for epoch in range(train_epoch): 
    for batch in range(n_batch):
        batch_xs, batch_ys = mnist.train.next_batch(batch_size) 
        sess.run(train_step, feed_dict = {x: batch_xs, y_: batch_ys}) 
    if(0==(epoch%test_epoch_n)):#每若干次预测test一次
        #计算test集的准确率
        correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 
        now_acc=sess.run(accuracy, feed_dict={x:mnist.test.images, y_: mnist.test.labels})
        print('epoch=',epoch,'ACC=',now_acc)
        if(now_acc>MaxACC):
            MaxACC = now_acc
            #tf.train.write_graph(sess.graph_def,'Model2','ModelSoftmax.pbtxt')
            saver.save(sess,'Model2/ModelSoftmax.ckpt')
            print('Save model! Now ACC=',MaxACC)

#计算最终test集的准确率
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 
print('Train OK! epoch=',epoch,'ACC=',sess.run(accuracy, feed_dict={x:mnist.test.images, y_: mnist.test.labels}))

#关闭sess
sess.close()

读取模型代码:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#mnist已经作为官方的例子,做好了数据下载,分割,转浮点等一系列工作,源码在tensorflow源码中都可以找到
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

# 配置每个 GPU 上占用的内存的比例
# 没有GPU直接sess = tf.Session()
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.95)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))

saver = tf.train.import_meta_graph('Model2/ModelSoftmax.ckpt.meta')

x_placeholder = tf.get_default_graph().get_tensor_by_name("InputFeature:0")
y_placeholder = tf.get_default_graph().get_tensor_by_name("InputLabel:0")
y=tf.get_default_graph().get_tensor_by_name("NetOutput:0")

correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_placeholder,1)) 
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 

gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.95)
with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:
    saver.restore(sess,'Model2/ModelSoftmax.ckpt') # 注意此处路径前添加"./"  
    print('Load Model OK!')
    print('ACC=',sess.run(accuracy, feed_dict={x_placeholder:mnist.test.images,y_placeholder: mnist.test.labels}))

pb方式还没弄明白怎么打包保存的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值