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

问题描述

在 numpy 中,有两个相同形状的数组,xy,可以做这样的切片 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)

参见 tf.boolean_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