Python 试图在Tensorflow中使用未初始化的值变量(使用了sess.run(tf.global\u variables\u initializer())
我尝试将我的神经网络模型和restore()函数划分为随机权重为零。 以下是模型代码: (工作正常) 下面是函数:Python 试图在Tensorflow中使用未初始化的值变量(使用了sess.run(tf.global\u variables\u initializer()),python,python-2.7,machine-learning,tensorflow,neural-network,Python,Python 2.7,Machine Learning,Tensorflow,Neural Network,我尝试将我的神经网络模型和restore()函数划分为随机权重为零。 以下是模型代码: (工作正常) 下面是函数: 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
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) 它一直在给我写信
FailedPremissionError(回溯见上文):尝试在此行中使用未初始化的值变量:
update = tf.scatter_update(ones_mask, index_num, zeroes)
不管怎样。我读过这些主题:和(以及许多其他主题),但来自这些主题的建议无助于修复我的bug。
我不明白,只要我运行tf.global_variables_initializer(),初始化有什么问题
2) 所有的权重似乎都设置为零而不是一半,我不明白为什么
请帮帮我,我真的被卡住了。仅为了记录(以及其他找到本文的人),方法名称已更改,如以下页面所示:
您应该像这样运行initialize\u all\u variables()
方法:
import tensorflow as tf
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
有些变量的初始化相互依赖。这是一个众所周知的问题。请参阅以获取讨论和信息solutions@YaroslavBulatov,谢谢,这帮助我解决了第一个问题。但是,我仍然不太明白为什么所有的权重似乎都是零。我不确定这是否相关,但我以前遇到过一个问题:函数中的变量不受全局变量初始化器()的影响,并且它也有助于调用局部变量初始化器()。这似乎有帮助……你能给出一个最小的、独立的例子来说明剩余的问题吗?它越小,我们就越有可能提供帮助。@PeterHawkins,我想在all ONE矩阵中将随机索引设置为零,然后在权重矩阵上将其相乘->部分权重被随机设置为零,下面是一个小代码段:提前谢谢。initialize_all_variables()不推荐使用,请参阅