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

新手上路,请多包涵

我想做这样的事情。

假设我们有一个张量 A。

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

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

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

Numpy中也有类似的操作。

np.flatnonzero(A) 返回扁平 A 中非零的索引。

x.ravel()[np.flatnonzero(x)] 根据非零索引提取元素。

这是这些操作 的链接

我如何使用 python 在 Tensorflow 中执行上述 Numpy 操作?

(矩阵是否展平并不重要。)

原文由 ByungSoo Ko 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

您可以使用 not_equalwhere 方法在 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

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

这足以从 A 选择零或非零元素。如果你想获得指数,你可以使用 where 方法如下:

 indices = tf.where(where)

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

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

原文由 Sergii Gryshkevych 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

原文由 user1098761 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题