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

12

我基本上想要在图表的中间提供输入选项,并从那里计算输出。我想到一个主意是使用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.})

你能详细说明一下你的问题吗?你需要什么类型的可选输入,并想要做什么? - Olivier Moindrot
我有一个类似于自编码器的图形,我想用与训练相同的图形将代码重构为瓶颈的输入。 - Lenar Hoyt
你能提供一下你现在使用 tf.placeholder_with_default 的代码部分吗?你想要修改哪一部分呢? - Olivier Moindrot
我已经添加了一些伪代码。 - Lenar Hoyt
1
PS,您可以通过获取/提供“<name>:0”来获取或提供TensorFlow图中的任何节点(打印tf.get_default_graph().as_graph_def()以获取<name>)。 - Yaroslav Bulatov
非常有帮助,谢谢! - Lenar Hoyt
1个回答

16

多亏了你的代码,我现在更好地理解了。

基本上模式是:

       input       <- you can feed here
         |        
     (encoder)
         |
     bottleneck    <- you can also feed here instead
         |
     (decoder)
         |
       output

您需要两种用例:

  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})

根据sess.run()的文档:

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接