tensorflow:函数内部变量的初始化

时间:2017-07-26 02:23:25

标签: python machine-learning tensorflow

Newbee to tensorflow。我试图用以下代码编写一些简单的网络:

import tensorflow as tf 
import tensorflow.contrib as tfc
import tensorflow.contrib.layers as tfcl

def generator_deconv(z, kernel):
    with tf.variable_scope("generator", reuse=True):
        weights = tf.get_variable("weights")
        biases = tf.get_variable("biases")
        result = tf.matmul(z, weights)
        result = tf.add(result, biases)
        result = tf.reshape(result, tf.stack([tf.shape(result)[0],13,4,1]))
        result = tf.nn.conv2d_transpose(result, kernel, 
                output_shape=[tf.shape(result)[0],25,8,1], 
                strides=[1,2,2,1], 
                padding="SAME")
        result = tf.nn.conv2d_transpose(result, kernel, 
                output_shape=[tf.shape(result)[0],50,15,1], 
                strides=[1,2,2,1], 
                padding="SAME")
        result = tf.nn.conv2d_transpose(result, kernel, 
                output_shape=[tf.shape(result)[0],100,30,1], 
                strides=[1,2,2,1], 
                padding="SAME")    
        return result

kernel = tf.constant(1.0, shape=[4,4,1,1])
protype = tf.constant(1.0, shape=[3,4])
init = tf.global_variables_initializer()

config = tf.ConfigProto()
config.gpu_options.allocator_type = 'BFC'
config.gpu_options.allow_growth=True

with tf.variable_scope("generator"):
    t1 = tf.get_variable("weights",shape=[4,52])
    t2 = tf.get_variable("biases", shape=[52])

test = generator_deconv(protype,kernel)

with tf.Session(config=config) as sess:
    sess.run(init)
    sess.run(tf.shape(t1))
    sess.run(tf.shape(t2))
    sess.run(tf.shape(test))

但得到了错误:

  

tensorflow.python.framework.errors_impl.FailedPreconditionError:   试图使用未初始化的值生成器/权重

最后一行

sess.run(tf.shape(test))

检查了tensorflow的官方api,但仍然不知道代码有什么问题。

================================ UPDATE ============== ============

找到了两种解决方法

1.if替换

sess.run(init)

通过

sess.run(tf.global_variables_initializer())

然后整个代码工作。

OR

2.run

init = tf.global_variables_initializer()
with tf.Session(config=config) as sess:
    sess.run(init)
    sess.run(tf.shape(t1))
    sess.run(tf.shape(t2))
    sess.run(tf.shape(test))

它再次起作用。

但不明白为什么

1 个答案:

答案 0 :(得分:2)

我为您删除了部分代码:

init = tf.global_variables_initializer()

with tf.variable_scope("generator"):
    t1 = tf.get_variable("weights",shape=[4,52])
    t2 = tf.get_variable("biases", shape=[52])

with tf.Session(config=config) as sess:
    sess.run(init)
    sess.run(tf.shape(t1))

在保存调用global_variables_initializer()的结果后,可以在图形中添加变量。在您的修复中,您在将要初始化的所有变量添加到图形之后调用此函数,因此所有内容都已初始化。

希望这有帮助!