如何在TensorFlow中向图形添加可选输入?

Len*_*oyt 12 tensorflow

我基本上想要选择将输入提供给图形的中间并计算从那里输出的输出.我的一个想法是使用tf.placeholder_with_default默认值为零张量.然后我可以使用加法混合可选输入,但是在大形状上添加这似乎是很多不必要的计算.有没有更好的方法来实现这一目标?

input_enabled = tf.placeholder_with_default(tf.constant(1.), [1])

input_shape = [None, in_size]
input = tf.placeholder_with_default(tf.zeros(input_shape), input_shape)
// ...
bottleneck_shape = [None, bottleneck_size]
bottleneck = input_enabled * f(prev_layer) + tf.placeholder_with_default(tf.zeros(bottleneck_shape), bottleneck_shape)
// ...

// Using graph with input at first layer:
sess.run([output], feed_dict={input: x})

// Using graph with input at bottleneck layer:
sess.run([output], feed_dict={bottleneck: b, input_enabled: 0.})
Run Code Online (Sandbox Code Playgroud)

Oli*_*rot 16

感谢您的代码,我明白了.

架构基本上是:

       input       <- you can feed here
         |        
     (encoder)
         |
     bottleneck    <- you can also feed here instead
         |
     (decoder)
         |
       output
Run Code Online (Sandbox Code Playgroud)

你想要两个用例:

  1. 火车:将图像输入input,计算输出
  2. 测试:将代码输入瓶颈,计算输出

您无需为其创建占位符bottleneck,因为sess.run()您可以将值提供给图表中的非占位符:

input_shape = [None, in_size]
input = tf.placeholder(tf.float32, input_shape)
# ...

bottleneck = f(prev_layer)  # of shape [None, bottleneck_size]
# ...

# Using graph with input at first layer:
sess.run([output], feed_dict={input: x})

# Using graph with input at bottleneck layer:
sess.run([output], feed_dict={bottleneck: b})
Run Code Online (Sandbox Code Playgroud)

来自以下文件sess.run():

可选的feed_dict参数允许调用者覆盖图中的张量值.feed_dict中的每个键都可以是以下类型之一:

如果键是Tensor,则该值可以是Python标量,字符串,列表或numpy ndarray,可以转换为与该张量相同的dtype.此外,如果键是占位符,则将检查值的形状是否与占位符兼容.