【问题标题】:TensorFlow: "Attempting to use uninitialized value" in variable initializationTensorFlow:变量初始化中的“尝试使用未初始化的值”
【发布时间】:2016-06-30 16:36: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 at line :- parameters.append(tf.Variable(initial_parameters_of_hypothesis_function[i]))
  • 好的,initial_parameters_of_hypothesis_function 是 tf.variable 的数组吗?如果是这样,那是你的问题。
  • 是的,最后一行是 [1.0,1.0,1.0] 那么应该是什么?
  • 您能否在示例中包含生成 initial_parameters_of_hypothesis_function 的代码? (也使它更小,删除行后的所有内容,但除外)

标签: python machine-learning linear-regression tensorflow


【解决方案1】:

运行这个:

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

或者(取决于您拥有的 TF 版本):

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

【讨论】:

【解决方案2】:

从代码示例中不是 100% 清楚,但是如果列表 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 键解释为张量:无法将 int 转换为张量。在行 session.run(train, feed_dict=feed)
  • 错误信息告诉你出了什么问题:feed 字典的键必须是 Tensor 对象(通常是 tf.placeholder() 张量)而不是 int 值。您可能想用feed[x[j]] = array 替换feed[j] = array。
  • 运行train 操作(由tf.train.GradientDescentOptimizer().minimize(loss) 返回)同时输入不同的训练示例似乎是一个好的开始。如果您有更具体的问题,请随时提出其他问题!
  • 虽然现在我的代码运行正确,但它给出的参数值与我初始化的初始值相同
  • 如果您的参数停留在局部最小值,则可能会发生这种情况。一个常见的错误是将所有权重初始化为零 - 相反,您应该随机初始化它们(使用例如tf.truncated_normal())。
【解决方案3】:

在调用初始化全局变量时,还有一个与顺序有关的错误。我的代码示例有类似的错误 FailedPreconditionError (参见上面的回溯): Attempting to use uninitialized value 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))

【讨论】:

    【解决方案4】:

    通常有两种初始化变量的方法,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】:

      我想给出我的解决方案,当我将行 [session = tf.Session()] 替换为 [sess = tf.InteractiveSession()] 时它会起作用。希望这对其他人有用。

      【讨论】:

      • 谢谢,这对我在 Jupyter Notebook 上运行时确实很有帮助。可以解释为什么它会起作用吗?
      • @shubhamsingh 交互式会话用于笔记本的整个实例。因此,您的会话始终处于打开状态。但是,如果我们使用 tensorflow.Session() 它仅适用于特定区域。例如我们使用 with 关键字,例如 (with tf.Session as sess:)
      【解决方案6】:

      同时运行:

      sess.run(tf.global_variables_initializer())

      sess.run(tf.local_variables_initializer())

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-02
        相关资源
        最近更新 更多