使用布尔张量进行Tensorflow索引

使用布尔张量进行Tensorflow索引

本文介绍了使用布尔张量进行Tensorflow索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在numpy中,有两个形状相同的数组, x y ,可以进行切片像这样 y [x> 1] 。你如何在tensorflow中实现相同的结果? y [tf.greater(x,1)] 不起作用且 tf.slice 不支持任何内容像这样。有没有办法立即用布尔张量索引或当前不支持?

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?

推荐答案

尝试:

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)

参见

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

EDIT: another (better ?) way to do it:

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]

这篇关于使用布尔张量进行Tensorflow索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 10:07