使用布尔张量进行Tensorflow索引

pyt*_*hor 19 python indexing tensorflow

在numpy中,有两个相同形状的数组,x并且y可以像这样做切片y[x > 1].你如何在张量流中获得相同的结果?y[tf.greater(x, 1)]不起作用,tf.slice也不支持这样的事情.有没有办法立即用布尔张量索引或者当前是不支持的?

Mr_*_*s_D 15

尝试:

ones = tf.ones_like(x) # create a tensor all ones
mask = tf.greater(x, ones) # boolean tensor, mask[i] = True iff x[i] > 1
slice_y_greater_than_one = tf.boolean_mask(y, mask)
Run Code Online (Sandbox Code Playgroud)

请参见tf.boolean_mask

编辑:另一种(更好?)方式:

import tensorflow as tf

x = tf.constant([1, 2, 0, 4])
y = tf.Variable([1, 2, 0, 4])
mask = x > 1
slice_y_greater_than_one = tf.boolean_mask(y, mask)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print (sess.run(slice_y_greater_than_one)) # [2 4]
Run Code Online (Sandbox Code Playgroud)


Jac*_*per 6

我不会说它完全没有实现.双重否定怎么样?

Tensorflow实际上支持相当多的切片和切块,尽管语法可能稍微不那么漂亮.例如,如果要创建一个等于ywhen x>1但等于0 的新数组,否则你肯定可以这样做.查看比较运算符,例如

masked = tf.greater(x,1)
zeros = tf.zeros_like(x)
new_tensor = tf.where(masked, y, zeros)
Run Code Online (Sandbox Code Playgroud)

另一方面,如果你想创建一个新的数组,其中只包含x>1你可以通过wheregather函数结合来实现的那些人.详细信息gather可以在

https://www.tensorflow.org/versions/master/api_docs/python/array_ops/slicing_and_joining

PS.当然,x>1对于x...来说是不可区分的.tf可能很棒,但它不起作用魔法:).


Yar*_*tov 3

目前尚未实现,这是跟踪进度的 GitHub 问题 - https://github.com/tensorflow/tensorflow/issues/206

  • 现在正在跟踪:https://github.com/tensorflow/tensorflow/issues/4639 (2认同)