In numpy, with two arrays of the same shape, x
and y
, it is possible to do slices like this y[x > 1]
. How do you achieve the same result in tensorflow? y[tf.greater(x, 1)]
doesn't work and tf.slice
doesn't support anything like this either. Is there a way to index with a boolean tensor right now or is that currently unsupported?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- batch_dot with variable batch size in Keras
- How to get the background from multiple images by
- Evil ctypes hack in python
Was looking for similar capability to reduce a TensorFlow.js tensor by a defined criteria, but TensorFlow.js does not have the boolean_mask function. After much hair pulling and teeth gnashing, cooked up the following, which essentially sums up the total number of true criteria, and then simply selects the topk values to create the subset tensor.
And to create a subset tensor of values less than or equal to 1, it's a matter of using tf.neg on the tensor as there is no bottomk function, and then after obtaining the subset tensor via topk, applying tf.neg again to restore the original values.
Try:
See tf.boolean_mask
EDIT: another (better ?) way to do it:
This is not implemented at this moment, here's GitHub issue tracking the progress -- https://github.com/tensorflow/tensorflow/issues/206
tf.boolean_mask
does the job, but on some platforms like Raspberry Pi or OSX, the operation is not supported in Tensorflow wheel distributions (Check this tf.boolean_mask not supported on OSX. So an alternative is to usewhere
andgather
as @Jackson Loper suggested. For example:I would not say it is completely not implemented. How's that for a double negative?
Tensorflow actually supports quite a lot of slicing and dicing, although the syntax may be slightly less pretty. For example, if you want to create a new array which is equal to
y
whenx>1
but equal to 0 otherwise, you can definitely do that. Check out comparison operators e.g.If, on the other hand, you want to make a new array which contains only the guys where
x>1
you can do that by combiningwhere
with thegather
function. Details forgather
can be found athttps://www.tensorflow.org/versions/master/api_docs/python/array_ops/slicing_and_joining
PS. Of course,
x>1
is not differentiable with respect tox
... tf may be great, but it doesn't work magic :).