美文网首页深度学习-推荐系统-CV-NLP
[专题2]tensorflow model save and r

[专题2]tensorflow model save and r

作者: 斐波那契的数字 | 来源:发表于2017-12-11 22:34 被阅读145次

二、进阶

Question:

After you train a model in Tensorflow:

1. How do you save the trained model?

2. How do you later restore this saved model?

在入门过程中是使用了saver = tf.train.import_meta_graph('保存的模型文件')

saver.restore(sess,tf.train.latest_checkpoint('指定CKPT文件')) 方法来保存并恢复图中的变量。

程序设计目标

下面我们会将MNIST--手写数字识别为例,回答上述的连个问题。

首先是构建CNN模型,(如何构建,请参考[专题1]TensorFlow构造神经网络(1)

然后再使用另一个文件去恢复保存的图以及模型,并在另一个文件里使用保存的图来做预测.

Train and Save

#-*-coding:UTF-8-*-

import tensorflow as tf

'''

@todo: train and save MNIST model

@author: lee

@Date: 2017 12/11

'''

from tensorflow.examples.tutorials.mnist import input_data

with tf.name_scope('dropout'):

keep_prob = tf.placeholder(tf.float32,name='keep_prob')

h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

with tf.name_scope('fc2'):

W_fc2 = weight_variable([1024, 10])

b_fc2 = bias_variable([10])

y_conv = tf.add(tf.matmul(h_fc1_drop, W_fc2), b_fc2, name='output')

return y_conv, keep_prob

# define basic ops

def con2d(x,W):

'''

conv2D return a 2D convolution layer with full stride

'''

return tf.nn.conv2d(x,W,stride=[1,1,1,1],padding='SAME')

def max_pool2x2(x): # max_pool2x2

'''

max pool ops, with classical strides

'''

return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1, 2, 2, 1],padding='SAME')

def weight_variable(shape):

'''

weight variable generates a weight variable of a given shape

'''

initial = tf.truncated_normal(shape, stddev=0.1)

return tf.Variable(initial)

def bias_variable(shapes):

'''

'''

initial = tf.constant(0.1,shape=shapes)

return tf.Variable(initial)

def conv2d(x,W):

return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')

def pool2d(x):

return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')

# define training model

def model(x):

'''

args:

x : an input tensor with dimensions(N_samples,784), where 784 is the number of pixels in a standard MNIST image

return a tupls(y, keep_prob) , where y is a tensor of shape(N_samples,10), with values equals to the logits of classifiing the digit into one of 10 classes(0-9), keep_prob is a scalar placeholder for probability od droupout.

'''

# 1st Layer

with tf.name_scope('reshape'):

x_image= tf.reshape(x,[-1,28,28,1]) #[bathes,hight,width,channels]

with tf.name_scope('conv1'):

W_conv1=weight_variable([5,5,1,32]) #[conv_W, conv_H,conv_Deep(channel bbefore conv),connal after conv]

b_conv1=bias_variable([32])

h_conv1=tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)

with tf.name_scope('pool1'):

h_pool1 = max_pool2x2(h_conv1)

with tf.name_scope('conv2'):

W_conv2 = weight_variable([5, 5, 32, 64])

b_conv2 = bias_variable([64])

h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)

with tf.name_scope('pool2'):

h_pool2 = max_pool2x2(h_conv2)

with tf.name_scope('fc1'):

W_fc1 = weight_variable([7 * 7 * 64, 1024])

b_fc1 = bias_variable([1024])

h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])

h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

# impoty data

# /home/lee/data

mnist=input_data.read_data_sets('/home/lee/data/', one_hot=True)

x=tf.placeholder(tf.float32, [None, 784], name='input_x')

y_=tf.placeholder(tf.float32, [None, 10], name='input_y_')

# Build the graph for the deep net

y_conv, keep_prob = model(x)

with tf.name_scope('loss'):

cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_,logits=y_conv)

cross_entropy = tf.reduce_mean(cross_entropy)

with tf.name_scope('adam_optimizer'):

train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

with tf.name_scope('accuracy'):

correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))

correct_prediction = tf.cast(correct_prediction, tf.float32)

accuracy = tf.reduce_mean(correct_prediction)

graph_location = '/tmp/graph'

print('Saving graph to: %s' % graph_location)

train_writer = tf.summary.FileWriter(graph_location)

train_writer.add_graph(tf.get_default_graph())

saver=tf.train.Saver(tf.global_variables())

with tf.Session() as sess:

sess.run(tf.global_variables_initializer())

for i in range(300):  #20000

batch = mnist.train.next_batch(50)

if i % 100 == 0:

train_accuracy = accuracy.eval(feed_dict={x:batch[0],y_: batch[1], keep_prob: 1.0 })

print('step %d, training accuracy %g' % (i, train_accuracy))

save_path='/tmp/tf_model/model_'+'%d'%i

print('%s' % save_path)

saver.save(sess, save_path)

train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

以上程序片段为将训练好的模型保存下来。保存的位置是可以通过自己写的输出看出来的:

Restory

模型在/tmp/tf_model/ 目录下, 接下来在入门的基础上,进行修改:

导入tensorfow 工具库; 导入手写体使用工具库.

#*-*coding:UTF-8-*-

import tensorflow as tf

from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('/home/lee/data/',one_hot=True)

恢复文件:

sess1 = tf.Session()

saver1 = tf.train.import_meta_graph('/tmp/tf_model/model_200.meta')  # load graph

saver1.restore(sess1, '/tmp/tf_model/model_200')  # load variables (remember no extension of file)

# saver1.restore(sess1, tf.train.latest_checkpoint('G:/tf_model/')) # or this

graph = tf.get_default_graph()  # get graph

恢复输入和输出所需要的tensor

x = graph.get_tensor_by_name('input_x:0') # input image

y_ = graph.get_tensor_by_name('input_y_:0')  # input label

y_conv = graph.get_tensor_by_name('fc2/output:0')  # output result from deepNN (predict label)

keep_prob_ = graph.get_tensor_by_name('dropout/keep_prob:0')  # keep probability

测试所需要的操作:

# accuracy calculation

correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))  # compare predict result and label

correct_prediction = tf.cast(correct_prediction, tf.float32)  # convert bool to float

accuracy1 = tf.reduce_mean(correct_prediction)  # calculate mean accuracy

for j in range(10): testSample_start = j * 50 # start num of test sample of one batch testSample_end = (j + 1) * 50 # end num of test sample of one batchprint('test %d accuracy %g' % (j, accuracy1.eval(session=sess1, feed_dict={x:mnist.test.images[testSample_start:testSample_end], y_: mnist.test.labels[testSample_start:testSample_end], keep_prob_: 1.0}))) # feed data for test

输出:

相关文章

网友评论

    本文标题:[专题2]tensorflow model save and r

    本文链接:https://www.haomeiwen.com/subject/vjgwixtx.html