为什么函数内部的变量未初始化?

时间:2019-10-03 04:53:53

标签: tensorflow

以下是我的代码摘录: enter image description here

然后运行此命令: enter image description here

,尽管我什至尝试过tf.initialize_all_variables(),但仍收到此错误 enter image description here

我能知道为什么函数[linear_layer]内的变量未初始化吗?

1 个答案:

答案 0 :(得分:1)

您应该显式创建诸如out之类的变量,以使tensorflow知道要评估哪个图形元素。在原始代码中,调用tf.global_variables_initializer()时并没有构建图形。这就是W未初始化的原因。

def linear_layer(input, units):
    W = tf.Variable(initial_value=glorot(shape=(input.get_shape().as_list()[1], units)), name="W")
    B = tf.Variable(initial_value=tf.zeros(shape=(input.get_shape().as_list()[0], 1)), name="B")
    out = tf.matmul(input, W) + B
    return out

out = linear_layer(input=tf.constant([[1.,2.,3.],[4.,5.,6.]]), units=10)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    sess.run(tf.local_variables_initializer())
    print(sess.run(out))

# [[ 0.8285629   0.7860288   1.8736962   0.4321289  -0.9692887  -1.638855
#   -0.19338632  0.5580156  -0.13394058  1.6745124 ]
#  [ 1.9110355   1.2211521   3.2454844  -0.9029484  -2.0184612  -2.753471
#   -0.29346204  0.340119    0.04118478  2.893313  ]]