![](/img/trans.png)
[英]How to set minimum k elements in a dimension in pytorch tensor to a specific value?
[英]How to reduce dimension of a tensor with keeping specific indexed elements of that dimension?
维度的减少类似于 reduce_max() 所做的,不同之处在于我想要该维度中元素的特定索引,而不是简单地选择最大的索引。 例如,我有一个 2x3 张量 A = [[0,1,2],[2,2,0]]。 如果我应用 tf.argmax(A),我会得到索引张量 [1, 1, 0]。 我怎样才能使用这个索引张量 [1, 1, 0] 来得到张量为 tf.reduce_max(A, 0) = [2, 2, 2]?
我不直接使用 tf.reduce_max 的原因是我想使用不同的索引张量而不是 argmax 索引张量来减少维度或保留索引值而不是该维度的最大值。
您可以使用tf.gather_nd
函数来执行此操作,但您需要将该[1, 1, 0]
索引张量转换为 2D 张量。
这里我假设索引张量是一个 numpy 数组(您可以通过调用.numpy()
方法将 tensorflow 张量转换为 numpy 数组。
idx = np.array([1, 1, 0])
idx = np.c_[idx[:, np.newaxis], np.arange(len(idx))]
print(idx)
# Output:
# array([[1, 0],
# [1, 1],
# [0, 2]])
这意味着:在使用上面提到的tf.gather_nd
时选择 (row1, col0), (row1, col1), and (row0, col2)
A = tf.Variable([[0, 1, 2], [2, 2, 0]])
tf.gather_nd(A, idx)
会给你预期的[2, 2, 2]
张量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.