首页 > 解决方案 > 如何通过张量流中的索引获取元素?

问题描述

data = tf.constant( [ [ [0, 2, 4, 1], [1, 0, 0, 2] ], [ [1, 0, 4, 6], [2, 6, 3, 1] ] ] ) 
indices = tf.argmax(data, axis=2)

如何在张量流中得到结果[ [4 2], [6 6] ]?请帮我!!!!

标签: tensorflow

解决方案


tf.reduce_max()在你的情况下使用

data = tf.constant([[ [0, 2, 4, 1],[1, 0, 0, 2]], [ [1, 0, 4, 6], [2, 6, 3, 1] ]])
maximum_values = tf.reduce_max(data, reduction_indices=[2])
with tf.Session() as sess:
    p=sess.run(maximum_values)
    print(p)

[[4 2]
[6 6]]

编辑:要访问其他值,您可以按索引切片,然后使用tf.concator tf.stack。例如,如果你想得到[[0 2] [3 1]]你可以尝试

with tf.Session() as sess:
    p=sess.run(data[0][0][0:2])
    print(p)
    [0 2]

    q=sess.run(data[1][1][2:])
    print(q)
    [3 1]

    r=sess.run(tf.stack([p,q],0))
    print(r)
    [[0 2]
    [3 1]]

推荐阅读