我想使用保留尺寸的 argmax 作为子张量。我有:
m, argm = T.max_and_argmax(a, axis=axis, keepdims=True)
我想在 a
中将这些值设置为零。 IE。我需要使用T.set_subtensor
。要使用它,我需要在 argm
处指定 a
的子张量 a_sub
,但我不太确定它是什么样的。对于多个维度,a_sub = a[argm]
是错误的。
这应该成立:
a_sub == T.max(a, axis=axis)
a_sub.shape == T.max(a, axis=axis).shape
最后我想做的是:
a = T.set_subtensor(a_sub, 0)
我当前的解决方案:
idx = T.arange(a.shape[axis]).dimshuffle(['x'] * axis + [0] + ['x'] * (a.ndim - axis - 1))
a = T.switch(T.eq(idx, argm), 0, a)
但是,a_sub = a[T.eq(idx, argm)]
不起作用。
最佳答案
您需要使用 Theano 的 advanced indexing features不幸的是,它与numpy's advanced indexing不同。 .
这是一个可以实现您想要的功能的示例。
更新:现在可以使用参数化轴,但请注意轴
不能是符号的。
import numpy
import theano
import theano.tensor as tt
theano.config.compute_test_value = 'raise'
axis = 2
x = tt.tensor3()
x.tag.test_value = numpy.array([[[3, 2, 6], [5, 1, 4]], [[2, 1, 6], [6, 1, 5]]],
dtype=theano.config.floatX)
# Identify the largest value in each row
x_argmax = tt.argmax(x, axis=axis, keepdims=True)
# Construct a row of indexes to the length of axis
indexes = tt.arange(x.shape[axis]).dimshuffle(
*(['x' for dim1 in xrange(axis)] + [0] + ['x' for dim2 in xrange(x.ndim - axis - 1)]))
# Create a binary mask indicating where the maximum values appear
mask = tt.eq(indexes, x_argmax)
# Alter the original matrix only at the places where the maximum values appeared
x_prime = tt.set_subtensor(x[mask.nonzero()], 0)
print x_prime.tag.test_value
关于numpy - argmax 结果作为子张量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31342134/