tensorflow,而不是正确恢复变量

时间:2017-10-02 08:28:26

标签: python session tensorflow neural-network

我正在处理tensorflow中的以下代码,并且它工作正常,但我决定保存我的会话并恢复它以便预测任何测试变量,我没有得到任何错误但是第二个代码我恢复了session输出始终为零,表示hidden_​​1_layer,hidden_​​2_layer,hidden_​​3_layer和output_layer为零,并且值已恢复,

为了正确保存/恢复会话,我无法弄清楚我必须改变什么

以下是我写的代码:

nn的培训代码:

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("/tmp/data", one_hot=True)

n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500

n_classes = 10
batch_size = 100

x = tf.placeholder('float',[None, 784])
y = tf.placeholder('float')
v1 = tf.Variable(3, name='v1')
v2 = tf.Variable(3, name='v2')

saver = tf.train.Saver()

hidden_1_layer = {'weights':tf.Variable(tf.random_normal([784, n_nodes_hl1])),
'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))}

hidden_2_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])),
'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))}

hidden_3_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])),
'biases':tf.Variable(tf.random_normal([n_nodes_hl3]))}

output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])),
'biases':tf.Variable(tf.random_normal([n_classes]))}


def neural_network_model(data):

    l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']) , hidden_1_layer['biases'])
    l1 = tf.nn.relu(l1)

    l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']) , hidden_2_layer['biases'])
    l2 = tf.nn.relu(l2)

    l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']) , hidden_3_layer['biases'])
    l3 = tf.nn.relu(l3)

    output = tf.matmul(l3, output_layer['weights']) + output_layer['biases']

    return output

def train_neural_network(x):
    prediction = neural_network_model(x)
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y))
    optimizer = tf.train.AdamOptimizer().minimize(cost)

    hm_epochs = 10

    with tf.Session() as sess:
        sess.run(tf.initialize_all_variables())

        for epoch in range(hm_epochs):
            epoch_loss = 0
            for _ in range(int(mnist.train.num_examples/batch_size)):
                epoch_x, epoch_y = mnist.train.next_batch(batch_size)
                _, c = sess.run([optimizer, cost], feed_dict = {x: epoch_x, y: epoch_y})
                epoch_loss += c

            print('Epoch', epoch, 'completed out of', hm_epochs,' loss:',epoch_loss)
            saver.save(sess, "C:/Users/jack/Desktop/test/model.ckpt")
        correct = tf.equal(tf.argmax(prediction,1), tf.argmax(y,1))
        accuracy = tf.reduce_mean(tf.cast(correct,'float'))
        print('Accuracy', accuracy.eval({x:mnist.test.images, y:mnist.test.labels}))


train_neural_network(x) 

我想要恢复会话并使用nn i预测值的代码:

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np

mnist = input_data.read_data_sets("/tmp/data", one_hot=True)

n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500

n_classes = 10
batch_size = 100

x = tf.placeholder('float',[None, 784])
y = tf.placeholder('float')
v1 = tf.Variable(3, name='v1')

saver = tf.train.Saver()

hidden_1_layer = {'weights':tf.Variable(tf.zeros([784, n_nodes_hl1])),
'biases':tf.Variable(tf.zeros([n_nodes_hl1]))}

hidden_2_layer = {'weights':tf.Variable(tf.zeros([n_nodes_hl1, n_nodes_hl2])),
'biases':tf.Variable(tf.zeros([n_nodes_hl2]))}

hidden_3_layer = {'weights':tf.Variable(tf.zeros([n_nodes_hl2, n_nodes_hl3])),
'biases':tf.Variable(tf.zeros([n_nodes_hl3]))}

output_layer = {'weights':tf.Variable(tf.zeros([n_nodes_hl3, n_classes])),
'biases':tf.Variable(tf.zeros([n_classes]))}


def neural_network_model(data):

    l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']) , hidden_1_layer['biases'])
    l1 = tf.nn.relu(l1)

    l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']) , hidden_2_layer['biases'])
    l2 = tf.nn.relu(l2)

    l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']) , hidden_3_layer['biases'])
    l3 = tf.nn.relu(l3)

    output = tf.matmul(l3, output_layer['weights']) + output_layer['biases']

    return output

def train_neural_network(data):
    prediction = neural_network_model(x)


    hm_epochs = 10

    with tf.Session() as sess:
        sess.run(tf.initialize_all_variables())
        saver.restore(sess,"C:/Users/jack/Desktop/test/model.ckpt")
        result = (sess.run(tf.argmax(prediction.eval(feed_dict={x:data}),1)))
        print(result)


train_neural_network([mnist.train.images[2]])     

print([mnist.train.labels[2]])

谢谢你的帮助

1 个答案:

答案 0 :(得分:1)

调用tf.train.Saver()时,它会为图表中可用的所有变量创建一个保护程序。因此应该在定义所有网络后创建:

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("/tmp/data", one_hot=True)

n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500

n_classes = 10
batch_size = 100

x = tf.placeholder('float',[None, 784])
y = tf.placeholder('float')
v1 = tf.Variable(3, name='v1')
v2 = tf.Variable(3, name='v2')

hidden_1_layer = {'weights':tf.Variable(tf.random_normal([784, n_nodes_hl1])),
'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))}

hidden_2_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])),
'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))}

hidden_3_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])),
'biases':tf.Variable(tf.random_normal([n_nodes_hl3]))}

output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])),
'biases':tf.Variable(tf.random_normal([n_classes]))}

saver = tf.train.Saver()

def neural_network_model(data):

(恢复相同)

您可以通过打印print(saver._var_list)

来检查将要保存的变量