二寒假学习计划:Tensorflow之保存加载模型
Posted 小可爱的大笨蛋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二寒假学习计划:Tensorflow之保存加载模型相关的知识,希望对你有一定的参考价值。
想要使用Movidius,但是Movidius只支持两种库,一个是Caffe另一个就是Tensorflow,相对来说的话,个人比较擅长Tensorflow,所以就选择了Tensorflow。
一、保存模型
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#载入数据
mnist = input_data.read_data_sets('./MNIST_data/',one_hot=True)
#定义数据大小
batch_size = 64
n_batch = mnist.train.num_examples // batch_size
print(batch_size,n_batch)
# 定义占位符,x和y
x = tf.placeholder(tf.float32,shape=[None,784],name='input_x')
y = tf.placeholder(tf.float32,shape=[None,10],name='input_y')
# 定义权重和偏置量
W = tf.Variable(tf.truncated_normal([784,10]),name='W')
b = tf.Variable(tf.zeros([10]) + 0.1,name='bc')
# 模型的输出
prediction = tf.nn.softmax(tf.matmul(x,W) + b,name='output')
# 定义熵代价函数
loss = tf.losses.softmax_cross_entropy(y,prediction,)
# 优化器
train_step = tf.train.AdamOptimizer(0.001).minimize(loss,name='train')
# 初始化
init = tf.global_variables_initializer()
# 计算准确率
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32),name='accuracy')
# 保存模型
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(init)
for epoch in range(10):
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)
acc = sess.run(accuracy,feed_dict=x:mnist.test.images,y:mnist.test.labels)
print("Iter: ,Accuracy: ".format(epoch+1,acc))
# 保存模型
saver.save(sess,save_path="./model/my_model.ckpt")
sess.close()
二、加载保存的模型
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('./MNIST_data',one_hot=True)
batch_size = 64
n_batch = mnist.train.num_examples // batch_size
print(batch_size,n_batch)
with tf.Session() as sess:
saver = tf.train.import_meta_graph("./model/my_model.ckpt.meta")
saver.restore(sess,"./model/my_model.ckpt")
# 根据tensor的名字获取对应的tensor
output = sess.graph.get_tensor_by_name('output:0')
accuracy = sess.graph.get_tensor_by_name('accuracy:0')
train_step = sess.graph.get_operation_by_name('train')
print(sess.run(accuracy,feed_dict='input_x:0':mnist.test.images,'input_y:0':mnist.test.labels))
for epoch in range(10):
for batch in range(n_batch):
batch_xs,batch_ys = mnist.train.next_batch(batch_size)
sess.run(train_step, feed_dict='input_x:0': batch_xs, 'input_y:0': batch_ys)
acc = sess.run(accuracy,feed_dict='input_x:0':mnist.test.images,'input_y:0':mnist.test.labels)
print("Iter: ,Accuracy: ".format(epoch+1,acc))
# 保存模型
sess.close()
以上是关于二寒假学习计划:Tensorflow之保存加载模型的主要内容,如果未能解决你的问题,请参考以下文章
TensorFlow2 入门指南 | 19 模型文件的保存与加载
TensorFlow2 入门指南 | 19 模型文件的保存与加载
24- 深度学习的模型保存和加载 (TensorFlow系列) (深度学习)