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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39219414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:00:11  来源:igfitidea点击:

In TensorFlow, how can I get nonzero values and their indices from a tensor with python?

pythontensorflowindices

提问by ByungSoo Ko

I want to do something like this.
Let's say we have a tensor A.

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

A = [[1,0],[0,4]]

And I want to get nonzero values and their indices from it.

我想从中获取非零值及其索引。

Nonzero values: [1,4]  
Nonzero indices: [[0,0],[1,1]]

There are similar operations in Numpy.
np.flatnonzero(A)return indices that are non-zero in the flattened A.
x.ravel()[np.flatnonzero(x)]extract elements according to non-zero indices.
Here's a linkfor these operations.

Numpy 中也有类似的操作。
np.flatnonzero(A)返回扁平化后
x.ravel()[np.flatnonzero(x)]的非零索引A.根据非零索引提取元素。
这是这些操作的链接

How can I do somthing like above Numpy operations in Tensorflow with python?
(Whether a matrix is flattened or not doesn't really matter.)

我怎样才能用 python 在 Tensorflow 中做类似上面 Numpy 操作的事情?
(矩阵是否变平并不重要。)

回答by Sergii Gryshkevych

You can achieve same result in Tensorflow using not_equaland wheremethods.

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

zero = tf.constant(0, dtype=tf.float32)
where = tf.not_equal(A, zero)

whereis a tensor of the same shape as Aholding Trueor False, in the following case

where是与A持有True或相同形状的张量False,在以下情况下

[[True, False],
 [False, True]]

This would be sufficient to select zero or non-zero elements from A. If you want to obtain indices you can use wheremethod as follows:

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

indices = tf.where(where)

wheretensor has two Truevalues so indicestensor will have two entries. wheretensor has rank of two, so entries will have two indices:

where张量有两个True值,因此indices张量将有两个条目。where张量的秩为 2,因此条目将具有两个索引:

[[0, 0],
 [1, 1]]

回答by user1098761

#assume that an array has 0, 3.069711,  3.167817.
mask = tf.greater(array, 0)
non_zero_array = tf.boolean_mask(array, mask)