TensorFlow:变量初始化中的“尝试使用未初始化的值”
machine-learning
python
tensorflow
4
0

我正在尝试使用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)
参考资料:
Stack Overflow
收藏
评论
共 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))
收藏
评论

运行这个:

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

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

init = tf.initialize_all_variables()
sess.run(init)
收藏
评论

从代码示例来看还不是100%清楚,但是如果列表initial_parameters_of_hypothesis_functiontf.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()))
收藏
评论

通常,有两种初始化变量的方法: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 。会议将是

在“主”上创建会话,根据需要恢复或初始化模型,或等待会话准备就绪。

sv = tf.train.Supervisor([parameters])
sess = sv.prepare_or_wait_for_session()
收藏
评论

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

收藏
评论
新手导航
  • 社区规范
  • 提出问题
  • 进行投票
  • 个人资料
  • 优化问题
  • 回答问题

关于我们

常见问题

内容许可

联系我们

@2020 AskGo
京ICP备20001863号