Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python tensorflow,未正确还原变量_Python_Session_Tensorflow_Neural Network - Fatal编程技术网

Python tensorflow,未正确还原变量

Python tensorflow,未正确还原变量,python,session,tensorflow,neural-network,Python,Session,Tensorflow,Neural Network,我在tensorflow中编写了下面的代码,它工作得很好,但是我决定保存会话并恢复它,以便预测任何测试变量,我没有得到任何错误,但是我恢复会话的第二个代码输出总是零,这意味着隐藏层,隐藏层,隐藏的_3_层和输出的_层为零,这些值被恢复 为了正确保存/恢复会话,我无法确定必须更改哪些内容 以下是我写的代码: nn的培训代码: import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' import tensorflow as tf from tensorfl

我在tensorflow中编写了下面的代码,它工作得很好,但是我决定保存会话并恢复它,以便预测任何测试变量,我没有得到任何错误,但是我恢复会话的第二个代码输出总是零,这意味着隐藏层,隐藏层,隐藏的_3_层和输出的_层为零,这些值被恢复

为了正确保存/恢复会话,我无法确定必须更改哪些内容

以下是我写的代码:

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预测值:

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]])
感谢您的帮助

当调用
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.\u var\u list)

来检查将要保存的变量。它起作用了,谢谢您的帮助。这个问题困扰了我两天。lol。但是为了让我更清楚,当我键入saver=tf.train.saver()时,它会保存已经声明的变量,但当我键入saver.save(sess)时,“C:/Users/jack/Desktop/test/model.ckpt”)当您调用
saver=tf.train.saver()时,它会更新已经保存的变量?@JackFarah
它只创建一个saver对象,还没有保存变量。但是,这个saver对象包含一个变量列表,以后将保存这些变量。这个列表将包含在
tf.train.saver()之前创建的所有变量
已调用。稍后调用
saver.save
时,将保存保存程序列表中的所有变量。