-
Notifications
You must be signed in to change notification settings - Fork 0
/
mnist_lenet5_test.py
57 lines (50 loc) · 2.72 KB
/
mnist_lenet5_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# utf-8
# 测试复现了节点 计算模型在测试集中的准确率
import time
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import mnist_lenet5_forward
import mnist_lenet5_backward
import numpy as np
TEST_INTERVAL_SECS = 5 # 定义程序循环间隔时间是5s
def test(mnist): # 将mnist数据集读入test函数
with tf.Graph().as_default() as g: # 复现计算图
x = tf.placeholder(tf.float32,[
mnist.test.num_examples,
mnist_lenet5_forward.IMAGE_SIZE,
mnist_lenet5_forward.IMAGE_SIZE,
mnist_lenet5_forward.NUM_CHANNELS
])
y_ = tf.placeholder(tf.float32,[None,mnist_lenet5_forward.OUTPUT_NODE])
y = mnist_lenet5_forward.forward(x,False,None) # 利用前向传播过程计算出y的值
# 由于使用训练好的网络,所以所有神经元都要参与运算,不使用dropout
# 实例化带滑动平均的saver对象,这样所有参数在会话中被加载时会被赋值为各自的滑动平均值
ema = tf.train.ExponentialMovingAverage(mnist_lenet5_backward.MOVING_AVERAGE_DECAY)
ema_restore = ema.variables_to_restore()
saver = tf.train.Saver(ema_restore)
# 计算准确率
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
while True:
with tf.Session() as sess: # 在with结构中加载ckpt,将滑动平均值赋给各个参数
ckpt = tf.train.get_checkpoint_state(mnist_lenet5_backward.MODEL_SAVE_PATH)
if ckpt and ckpt.model_checkpoint_path: # 判断是否存在模型
saver.restore(sess,ckpt.model_checkponint_path) # 若存在恢复模型到当前会话
global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1] # 恢复global值
reshaped_x = np.reshape(mnist.test.image,(
mnist.test.num_example,
mnist_lenet5_forward.IMAGE_SIZE,
mnist_lenet5_forward.IMAGE_SIZE,
mnist_lenet5_forward.NUM_CHANNELS))
accuracy_score = sess.run(accuracy,feed_dict={x:reshaped_x,y_:mnist.test.labels}) # 执行准确率计算
print('After %s training step(s),test accuracy = %g' % (global_step,accuracy_score))
else:
print('No checkpoint file found')
return
time.sleep(TEST_INTERVAL_SECS)
# 读入数据集调用test函数
def main():
mnist = input_data.read_data_sets('./data/',one_hot = True)
test(mnist)
if __name__ == '__main__':
main()