在 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
In TensorFlow, how can I get nonzero values and their indices from a tensor with python?
提问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_equal和where方法在 Tensorflow 中获得相同的结果。
zero = tf.constant(0, dtype=tf.float32)
where = tf.not_equal(A, zero)
where
is a tensor of the same shape as A
holding True
or 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 where
method as follows:
这足以从 中选择零或非零元素A
。如果要获取索引,可以使用where
如下方法:
indices = tf.where(where)
where
tensor has two True
values so indices
tensor will have two entries. where
tensor 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)