在 TensorFlow 中,如何使用 python 从张量中获取非零值及其索引? [英] In TensorFlow, how can I get nonzero values and their indices from a tensor with python?

查看:109
本文介绍了在 TensorFlow 中,如何使用 python 从张量中获取非零值及其索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to do something like this.
Let's say we have a tensor 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]]

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

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 link for these operations.

如何使用 python 在 Tensorflow 中执行上述 Numpy 操作?
(矩阵是否展平并不重要.)

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

推荐答案

您可以使用 not_equalwhere 方法.

You can achieve same result in Tensorflow using not_equal and where methods.

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

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

where is a tensor of the same shape as A holding True or False, in the following case

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

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

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:

indices = tf.where(where)

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

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:

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

这篇关于在 TensorFlow 中,如何使用 python 从张量中获取非零值及其索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆