tensorflow学习笔记--restore使用模型

代码:
import tensorflow as tf
import numpy as np
import scipy
from scipy import ndimage
#graph = tf.Graph()

# 定义计算图---start  (计算图应与训练时的计算图相同)
X = tf.placeholder(name='X', shape=(None, 64, 64, 3), dtype=tf.float32)
Y = tf.placeholder(name='Y', shape=(None, 6), dtype=tf.float32)

W1 = tf.Variable( tf.random_normal([4,4,3,8], -1, 1), name='W1')
W2 = tf.Variable( tf.random_normal([2, 2, 8, 16], -1, 1),name='W2')

Z1 = tf.nn.conv2d(input=X, filter=W1, strides=(1, 1, 1, 1), padding='SAME')
# RELU
A1 = tf.nn.relu(Z1)
# MAXPOOL: window 8x8, sride 8, padding 'SAME'
P1 = tf.nn.max_pool(value=A1, ksize=(1, 8, 8, 1), strides=(1, 8, 8, 1), padding='SAME')
# CONV2D: filters W2, stride 1, padding 'SAME'
Z2 = tf.nn.conv2d(input=P1, filter=W2, strides=(1, 1, 1, 1), padding='SAME')
# RELU
A2 = tf.nn.relu(Z2)
# MAXPOOL: window 4x4, stride 4, padding 'SAME'
P2 = tf.nn.max_pool(value=A2, ksize=(1, 4, 4, 1), strides=(1, 4, 4, 1), padding='SAME')
# FLATTEN
P2 = tf.contrib.layers.flatten(inputs=P2)
# FULLY-CONNECTED without non-linear activation function (not not call softmax).
# 6 neurons in output layer. Hint: one of the arguments should be "activation_fn=None"
Z3 = tf.contrib.layers.fully_connected(P2, 6, activation_fn=None)
#定义模型图---end
#saver = tf.train.Saver()  saver定义在sess里外都可以
with tf.Session() as sess:

    check_point_path = 'saved_model/' # 保存好模型的文件路径

    ckpt = tf.train.get_checkpoint_state(checkpoint_dir=check_point_path)
    saver = tf.train.Saver()
    # 从模型中恢复参数
    saver.restore(sess, ckpt.model_checkpoint_path)  # 讀取成功,然后就可以使用模型参数进行预测,或者测试了。
    fname = "images/thumbs_up.jpg"
    image = np.array(ndimage.imread(fname, flatten=False))
    my_image = scipy.misc.imresize(image, size=(64, 64))
    my_image = np.expand_dims(my_image, 0)
    y = sess.run(Z3, feed_dict={X: my_image})
    print(np.argmax(np.squeeze(y)))

你可能感兴趣的:(tensorflow)