在控制流和条件语句中使用张量

Using Tensors in control flow and conditional statements

我对如何在控制流语句中使用张量(没有会话)感兴趣。


我的意思的一个例子是:

myTensor = tf.where(myOtherTensor) # shape == [None, 2]
numLoops = tf.shape(myTensor)[0] # Results in tensor of shape [1]
for i in xrange(numLoops):
     # ...

我可以将 numLoops(张量)传递给 xrange() 吗?如果没有,还有其他方法吗?


另一个例子是:

myTensor = tf.in_top_k(myOtherTensor1, myOtherTensor2, 5) # Tensor of bools
myCondition = myTensor[0] # Results in tensor of shape [1] of type bool
if myCondition:
     # ...

我的问题:张量(没有特定会话)可以按上述方式使用吗?

如果我有一个会话,我可以简单地评估那些单元素张量,然后使用它们。如果直到运行时我才知道具体的值,那么必须有一种使用这些值的方法。

我可以预见的问题:也许循环会使生成图形变得不可能,因为您不知道包含的操作将被执行多少次?但是存储循环的操作并在运行时简单地应用它们正确的次数似乎是微不足道的。

如果有任何不清楚的地方,请告诉我,我会提供更多详细信息。

TensorFlow 在 the tensorflow.python.ops.control_flow_ops module 中包含对 in-graph 控制流的实验性支持。 (N.B。 这些操作的接口可能会发生变化!使用风险自负!)


条件支持(您的第二个案例)将出现在下一个版本中,并且最近添加到 public API(如果您从源代码构建)。它目前在 TensorFlow 附带的一些库中使用,例如 RNN cell(当序列长度已知时,它用于提前停止)。

tf.cond() 运算符接受一个布尔值 Tensor 作为谓词,以及两个 lambda 表达式;和 returns 一个或多个值。

你的程序看起来像这样:

if_true = lambda: ...  # Value to return if `myCondition` is true
if_false = lambda: ...  # Value to return if `myCondition` is false

result = tf.cond(myCondition, if_true, if_false)

迭代(您的第一个案例)可以使用 While() higher-order 运算符处理。本质上,您可以将程序编写为(伪代码):

i = 0
while i < tf.rank(myTensor):
  # ...

...大致表示为:

from tensorflow.python.ops import control_flow_ops as cfo

i = tf.constant(0)
condition = lambda i: tf.less(i, tf.rank(myTensor))
body = lambda x: ...
inital_accumulator = ...  # will be bound to `x` in first iteration of `body`.

# `result` will contain the value returned from the final iteration of `body`.
result = cfo.While(condition, body, [initial_accumulator])

请注意,While() 运算符要求您为所有循环变量指定初始值(在本例中为 initial_accumulator)。循环常量将像正常的 Python lambda 一样被捕获。