在TensorFlow中,如何从python的张量中获取非零值及其索引?

Byu*_* Ko 23 python indices tensorflow

我想做这样的事情.
假设我们有一个张量A.

A = [[1,0],[0,4]]
Run Code Online (Sandbox Code Playgroud)

我希望从中获得非零值及其指数.

Nonzero values: [1,4]  
Nonzero indices: [[0,0],[1,1]]
Run Code Online (Sandbox Code Playgroud)

Numpy也有类似的操作.根据非零指数
np.flatnonzero(A),在展平的A.
x.ravel()[np.flatnonzero(x)]extract元素中返回非零的索引.
这是这些操作的链接.

我怎样才能在Tensorflow中使用python执行上面的Numpy操作?
(矩阵是否扁平化并不重要.)

Ser*_*ych 35

您可以使用not_equalwhere方法在Tensorflow中获得相同的结果.

zero = tf.constant(0, dtype=tf.float32)
where = tf.not_equal(A, zero)
Run Code Online (Sandbox Code Playgroud)

where是作为相同形状的张量A保持TrueFalse,在以下的情况下

[[True, False],
 [False, True]]
Run Code Online (Sandbox Code Playgroud)

这足以从中选择零或非零元素A.如果要获取索引,可以使用以下where方法:

indices = tf.where(where)
Run Code Online (Sandbox Code Playgroud)

where张量有两个True值,因此indices张量将有两个条目.where张量的等级为2,因此条目将有两个索引:

[[0, 0],
 [1, 1]]
Run Code Online (Sandbox Code Playgroud)


use*_*761 5

#assume that an array has 0, 3.069711,  3.167817.
mask = tf.greater(array, 0)
non_zero_array = tf.boolean_mask(array, mask)
Run Code Online (Sandbox Code Playgroud)

  • 负值也可以是非零。这不是返回索引。 (2认同)