尝试在Tensorflow中使用未初始化的值(已使用`sess.run(tf.global_variables_initializer())`!)

3
我将尝试将神经网络模型和设置随机权重为零的restore()函数分开。以下是模型代码:http://pastebin.com/TqN6kkeb(其正常工作)。
以下是该功能的代码:
from __future__ import print_function

import tensorflow as tf
tf.GraphKeys.VARIABLES = tf.GraphKeys.GLOBAL_VARIABLES
import random
from LogReg import accuracy
from LogReg import W
from LogReg import x,y


# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)


def restore(model_file):

    with tf.Session() as sess:

        new_saver = tf.train.import_meta_graph(model_file + ".meta")
        new_saver.restore(sess, model_file)

        with tf.variable_scope("foo", reuse=True):
            temp_var = tf.get_variable("W")
            size_2a = tf.get_variable("b")

        size_2 = tf.shape(size_2a).eval()[0]
        size_1 = tf.shape(temp_var).eval()[0]

        ones_mask = tf.Variable(tf.ones([size_1, size_2]))
        arg = random.sample(xrange(size_1), size_1/2)
        index_num=tf.convert_to_tensor(arg, dtype=tf.int32)
        print("om", ones_mask)
        print("index", index_num)
        print(W)

        zeroes = tf.zeros([size_1/2, size_2])
        update = tf.scatter_update(ones_mask, index_num, zeroes)
        print(update)

        assign_op = W.assign(tf.mul(W, update))
        sess.run(update)
        sess.run(assign_op)
        init_op = tf.global_variables_initializer()
        sess.run(init_op)
        new_saver.save(sess, model_file)
        print("Accuracy_new:", accuracy.eval({x: mnist.test.images, y:mnist.test.labels}))

restore('./MyModel2')

问题如下: 1) 在这行代码中,它一直给我写 FailedPreconditionError (详见上面的 traceback):尝试使用未初始化的变量“Variable”。
update = tf.scatter_update(ones_mask, index_num, zeroes)

无论如何。我已经阅读了这些主题:Prettytensor: Attempting to use uninitialized valueUpdate a subset of weights in TensorFlow(以及许多其他主题),但那里的建议并没有帮助我解决问题。只要我运行tf.global_variables_initializer(),我就不明白初始化有什么问题。
2)所有的权重似乎都被设置为零而不是一半,我不知道为什么。
请帮忙,我真的卡住了。

您有变量的初始化彼此依赖。这是一个已知问题。请参见4920以获取讨论和解决方案。 - Yaroslav Bulatov
@YaroslavBulatov,谢谢,这有助于我解决第一个问题。然而,我仍然不太明白为什么所有的权重似乎都是零。 - TheDoctor
不确定是否相关,但我之前遇到过一个问题,即在def:函数内部的变量不受global_variables_initializer()的影响,而调用local_variable_initializer()也有所帮助... - VS_FF
@PeterHawkins,我想将全1矩阵中的随机索引设置为零,然后将其乘以权重矩阵->部分权重被随机设置为零,这是一个小代码片段:http://pastebin.com/z1T87AQZ提前致谢。 - TheDoctor
@PeterHawkins,我已经尽可能地简化了代码,但现在我无法监控准确性,因此我不太明白如何检查代码的工作情况,print(update)无法显示变量内部内容:http://pastebin.com/yrPAzzbi - TheDoctor
显示剩余3条评论
1个回答

0

initialize_all_variables()已被弃用,请参见https://www.tensorflow.org/versions/r1.2/api_docs/python/tf/initialize_all_variables - S Wang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接