TensorFlow:变量初始化中出现“尝试使用未初始化的值”错误

51

我正在尝试使用TensorFlow在Python中实现多元线性回归,但遇到了一些逻辑和实现问题。我的代码抛出以下错误:

Attempting to use uninitialized value Variable
Caused by op u'Variable/read'

理想情况下,weights输出应为[2, 3]

def hypothesis_function(input_2d_matrix_trainingexamples,
                        output_matrix_of_trainingexamples,
                        initial_parameters_of_hypothesis_function,
                        learning_rate, num_steps):
    # calculate num attributes and num examples
    number_of_attributes = len(input_2d_matrix_trainingexamples[0])
    number_of_trainingexamples = len(input_2d_matrix_trainingexamples)

    #Graph inputs
    x = []
    for i in range(0, number_of_attributes, 1):
        x.append(tf.placeholder("float"))
    y_input = tf.placeholder("float")

    # Create Model and Set Model weights
    parameters = []
    for i in range(0, number_of_attributes, 1):
        parameters.append(
            tf.Variable(initial_parameters_of_hypothesis_function[i]))

    #Contruct linear model
    y = tf.Variable(parameters[0], "float")
    for i in range(1, number_of_attributes, 1):
        y = tf.add(y, tf.multiply(x[i], parameters[i]))

    # Minimize the mean squared errors
    loss = tf.reduce_mean(tf.square(y - y_input))
    optimizer = tf.train.GradientDescentOptimizer(learning_rate)
    train = optimizer.minimize(loss)

    #Initialize the variables
    init = tf.initialize_all_variables()

    # launch the graph
    session = tf.Session()
    session.run(init)
    for step in range(1, num_steps + 1, 1):
        for i in range(0, number_of_trainingexamples, 1):
            feed = {}
            for j in range(0, number_of_attributes, 1):
                array = [input_2d_matrix_trainingexamples[i][j]]
                feed[j] = array
            array1 = [output_matrix_of_trainingexamples[i]]
            feed[number_of_attributes] = array1
            session.run(train, feed_dict=feed)

    for i in range(0, number_of_attributes - 1, 1):
        print (session.run(parameters[i]))

array = [[0.0, 1.0, 2.0], [0.0, 2.0, 3.0], [0.0, 4.0, 5.0]]
hypothesis_function(array, [8.0, 13.0, 23.0], [1.0, 1.0, 1.0], 0.01, 200)

你在哪一行代码上遇到了异常? - Daniel Slater
3
好的,initial_parameters_of_hypothesis_function是一个tf.variable数组吗?如果是的话,那就是你的问题。 - Daniel Slater
最后一行的确是[1.0, 1.0, 1.0],那么接下来应该是什么呢? - NEW USER
1
你能否在示例中包含生成假设函数初始参数的代码?(还需要将其缩小,删除异常行之后的所有内容) - Daniel Slater
在代码片段的最后,有一段代码用于初始化假设函数的初始参数。 - NEW USER
显示剩余2条评论
6个回答

71

运行此命令:

init = tf.global_variables_initializer()
sess.run(init)

或者(根据您所使用的 TensorFlow 版本):

init = tf.initialize_all_variables()
sess.run(init)

1
init = tf.global_variables_initializer() 初始化 = tf.global_variables_initializer() - norman_h
4
对不起,"initialize_all_variables"已经被废弃了。请参考以下链接获取更多信息:https://www.tensorflow.org/api_docs/python/tf/initialize_all_variables - Mr_and_Mrs_D
3
嗯,为什么这不是最佳答案? - Zuoanqh
@Zuoanqh 没错!我也有同样的问题。 - Srinivas Valekar

22

从代码示例中并不完全清楚,但如果列表 initial_parameters_of_hypothesis_function 是由 tf.Variable 对象组成的列表,那么行 session.run(init) 会失败,因为 TensorFlow 还不够智能以找出变量初始化中的依赖关系。为了解决这个问题,你应该更改创建 parameters 的循环以使用 initial_parameters_of_hypothesis_function[i].initialized_value(),它将添加必要的依赖项:

parameters = []
for i in range(0, number_of_attributes, 1):
    parameters.append(tf.Variable(
        initial_parameters_of_hypothesis_function[i].initialized_value()))

那个可以运行,但现在出错了:TypeError: 无法将feed_dict键解释为Tensor:无法将int转换为Tensor。在session.run(train,feed_dict = feed)的一行。 - NEW USER
3
错误信息告诉你出了什么问题:feed 字典的键必须是“张量”对象(通常是 tf.placeholder() 张量),而不是整数值。你可能想用 feed[x[j]] = array 替换 feed[j] = array - mrry
运行 train 操作(由 tf.train.GradientDescentOptimizer().minimize(loss) 返回)同时提供不同的训练样例似乎是一个不错的开始。如果您有更具体的问题,请随时提出另一个问题! - mrry
尽管现在我的代码运行正确,但它给出的参数值与我初始化时的初始值相同。 - NEW USER
如果您的参数被卡在局部最小值中,就会出现这种情况。一个常见的错误是将所有权重初始化为零 - 相反,您应该随机初始化它们(例如使用 tf.truncated_normal())。 - mrry
parameters.append(tf.Variable(initial_parameters_of_hypothesis_function[i]).initialized_value()) 这里不应该使用 initial_parameters_of_hypothesis_function,因为它是 OP 中的一个列表。此外,https://www.tensorflow.org/versions/r0.7/api_docs/python/state_ops.html#Variable.initialized_value 是对 API 较旧版本的引用,现在应该如何处理呢? - Mr_and_Mrs_D

5

通常有两种初始化变量的方法,1)使用如前面答案所述的sess.run(tf.global_variables_initializer());2)从检查点加载图形。

您可以按照以下方式操作:

sess = tf.Session(config=config)
saver = tf.train.Saver(max_to_keep=3)
try:
    saver.restore(sess, tf.train.latest_checkpoint(FLAGS.model_dir))
    # start from the latest checkpoint, the sess will be initialized 
    # by the variables in the latest checkpoint
except ValueError:
    # train from scratch
    init = tf.global_variables_initializer()
    sess.run(init)

第三种方法是使用tf.train.Supervisor。会话将会:

在'master'上创建一个会话,根据需要恢复或初始化模型,或等待会话准备好。

sv = tf.train.Supervisor([parameters])
sess = sv.prepare_or_wait_for_session()

5

还有另一个错误发生了,与调用初始化全局变量的顺序有关。我有一份代码样本也遇到了类似的错误FailedPreconditionError(请参见上面的回溯):尝试使用未初始化的值W

def linear(X, n_input, n_output, activation = None):
    W = tf.Variable(tf.random_normal([n_input, n_output], stddev=0.1), name='W')
    b = tf.Variable(tf.constant(0, dtype=tf.float32, shape=[n_output]), name='b')
    if activation != None:
        h = tf.nn.tanh(tf.add(tf.matmul(X, W),b), name='h')
    else:
        h = tf.add(tf.matmul(X, W),b, name='h')
    return h

from tensorflow.python.framework import ops
ops.reset_default_graph()
g = tf.get_default_graph()
print([op.name for op in g.get_operations()])
with tf.Session() as sess:
    # RUN INIT
    sess.run(tf.global_variables_initializer())
    # But W hasn't in the graph yet so not know to initialize 
    # EVAL then error
    print(linear(np.array([[1.0,2.0,3.0]]).astype(np.float32), 3, 3).eval())

您应该更改以下内容

from tensorflow.python.framework import ops
ops.reset_default_graph()
g = tf.get_default_graph()
print([op.name for op in g.get_operations()])
with tf.Session() as 
    # NOT RUNNING BUT ASSIGN
    l = linear(np.array([[1.0,2.0,3.0]]).astype(np.float32), 3, 3)
    # RUN INIT
    sess.run(tf.global_variables_initializer())
    print([op.name for op in g.get_operations()])
    # ONLY EVAL AFTER INIT
    print(l.eval(session=sess))

3

我想提供我的解决方案,只需将代码行[session = tf.Session()]替换为[sess = tf.InteractiveSession()]即可生效。希望对其他人有用。


谢谢,这对我在Jupyter Notebook上运行确实有帮助。但是能解释一下它为什么有效吗? - shubhamsingh
1
@shubhamsingh 交互式会话用于整个笔记本实例。因此,您的会话始终处于打开状态。但是,如果我们使用tensorflow.Session(),它仅适用于特定区域。例如,我们使用“with”关键字(如with tf.Session as sess:)。 - Srinivas Valekar

3

同时运行:

sess.run(tf.global_variables_initializer())

sess.run(tf.local_variables_initializer())


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