试图使用未初始化的值。 [Tensorflow]

时间:2018-02-22 19:38:57

标签: tensorflow initialization

这是我的代码:

def conv_pooling(data, sequence_length, filter_size, embedding_size, num_filters):
    filter_shape = [filter_size, embedding_size, 1, num_filters]
    w = tf.Variable(tf.truncated_normal(filter_shape,stddev = 0.1), 
    name = "w")
    b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name = 
    "b")
    conv = tf.nn.conv2d(
        item,
        w,
        strides = [1,1,1,1],
        padding = "VALID",
        name = "conv"
    )
    h = tf.nn.relu(tf.nn.bias_add(conv, b), name = "relu")
    pooled = tf.nn.max_pool(
        h,
        ksize = [1,sequence_length - filter_size + 1, 1, 1],
        strides = [1,1,1,1],
        padding = "VALID",
        name = "pool"
    )

    return pooled

init_op = tf.global_variables_initializer()
pooled_outputs = []
with tf.Session() as sess:

     sess.run(init_op)

     for i, filter_size in enumerate(filter_sizes):

         pooled = sess.run(conv_pooling(data, sequence_length, filter_size, embedding_size, num_filters), feed_dict = {embedded_chars: item})

         pooled_outputs.append(pooled)

这个'数据'是使用全局tf.placeholder'Imbedded_chars'的tf.Variable,所以不要担心它是否正常工作。发生错误是因为w和b无法初始化。

我也尝试了sess.run(tf.local_variables_initializer()),不能正常工作并返回相同的错误。有谁知道我可以在这里初始化w和b的方式吗?当你看到w的大小改变为for循环。

谢谢!

1 个答案:

答案 0 :(得分:1)

请参阅下面的代码。这就是为什么@mikkola意味着在初始化之前创建图表的原因。

// create your computation graph
pooled = conv_pooling(data, sequence_length, filter_size, embedding_size, num_filters)

// initialize the variables in the graph
init_op = tf.global_variables_initializer()

pooled_outputs = []

with tf.Session() as sess:

     sess.run(init_op)

     for i, filter_size in enumerate(filter_sizes):

         // run the graph to get your output
         output = sess.run([pooled], feed_dict = {embedded_chars: item})

         pooled_outputs.append(output)