【问题标题】:In tensorflow How could I get the min value index but except zero在张量流中我怎么能得到最小值索引但除了零
【发布时间】:2017-10-12 19:05:22
【问题描述】:

我想得到一个张量的最小值索引,但是值不是0。

a = np.array([[0, 3, 9, 0],
            [0, 0, 5, 7]])
tensor_a = tf.constant(a, dtype=tf.int32)
max_index = tf.argmax(tensor_a, axis=1)

上面的代码定义了一个常量张量,如果我使用tf.argmax,我会得到索引[2, 3]。我怎样才能在第一行获得 3 和在第二行获得 5 的索引,最小值但不是零。我想要得到的真正索引是 [1, 2]。 如何在tensorflow中实现,谢谢。

【问题讨论】:

  • 您在寻找什么?最大值分别为 9 和 5,在索引 2 和 3 处。您在寻找什么?
  • 我想获取除零以外的最小值索引。如何获得 tensor_a 中的最小值索引(应排除 0)。在上面的例子中,因为我不需要 0,所以第 1 行的最小值是 3,第 2 行的最小值是 5。代码应该返回 [1, 2]。
  • 可能是tf.min(tf.boolean_mask(x > 0)) 之类的?

标签: tensorflow


【解决方案1】:

这很可怕,但它确实有效:

with tf.Session() as sess:
    a = np.array([[0, 3, 9, 0],
                [0, 0, 5, 7]])
    tensor_a = tf.constant(a, dtype=tf.int64)
    row_max = tf.reshape(tf.reduce_max(a, axis=-1), [-1, 1]) + 1
    max_index = tf.argmin(tf.where(tensor_a > 0, tensor_a, row_max * tf.ones_like(tensor_a)), axis=1)
    print(max_index.eval()) # -> [1 2]

【讨论】:

    猜你喜欢
    • 2023-03-04
    • 2019-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多