gpt4 book ai didi

python - 沿多个维度的 Tensorflow argmax

转载 作者:太空宇宙 更新时间:2023-11-03 15:10:07 25 4
gpt4 key购买 nike

我是tensorflow的新手,我正在尝试获取张量中最大值的索引。这是代码:

def select(input_layer):

shape = input_layer.get_shape().as_list()

rel = tf.nn.relu(input_layer)
print (rel)
redu = tf.reduce_sum(rel,3)
print (redu)

location2 = tf.argmax(redu, 1)
print (location2)

sess = tf.InteractiveSession()
I = tf.random_uniform([32, 3, 3, 5], minval = -541, maxval = 23, dtype = tf.float32)
matI, matO = sess.run([I, select(I, 3)])
print(matI, matO)

这是输出:

Tensor("Relu:0", shape=(32, 3, 3, 5), dtype=float32)
Tensor("Sum:0", shape=(32, 3, 3), dtype=float32)
Tensor("ArgMax:0", shape=(32, 3), dtype=int64)
...

由于argmax函数中的dimension=1,Tensor("ArgMax:0") = (32,3)的形状。有没有什么方法可以在应用 argmax 之前获得 argmax 输出张量大小 = (32,) 且无需执行 reshape 操作>?

最佳答案

您可能不想要大小为 (32,) 的输出,因为当您沿多个方向 argmax 时,您通常希望获得最大值的坐标所有减小的尺寸。在您的情况下,您希望输出大小为 (32,2)

您可以像这样执行二维argmax:

import numpy as np
import tensorflow as tf

x = np.zeros((10,9,8))
# pick a random position for each batch image that we set to 1
pos = np.stack([np.random.randint(9,size=10), np.random.randint(8,size=10)])

posext = np.concatenate([np.expand_dims([i for i in range(10)], axis=0), pos])
x[tuple(posext)] = 1

a = tf.argmax(tf.reshape(x, [10, -1]), axis=1)
pos2 = tf.stack([a // 8, tf.mod(a, 8)]) # recovered positions, one per batch image

sess = tf.InteractiveSession()
# check that the recovered positions are as expected
assert (pos == pos2.eval()).all(), "it did not work"

关于python - 沿多个维度的 Tensorflow argmax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44288272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com