Numpy argmax结果作为子传感器

Numpy argmax结果作为子传感器,numpy,theano,Numpy,Theano,我想使用argmax作为子传感器,保留尺寸。我有: m, argm = T.max_and_argmax(a, axis=axis, keepdims=True) 我想在a中将这些值设置为零。即,我需要使用T.set\u子传感器。要使用它,我需要在argm处指定a的子传感器a_sub,但我不确定它是什么样子a_sub=a[argm]对于多个维度是错误的 这应包括: a_sub == T.max(a, axis=axis) a_sub.shape == T.max(a, axis=axis).s

我想使用argmax作为子传感器,保留尺寸。我有:

m, argm = T.max_and_argmax(a, axis=axis, keepdims=True)
我想在
a
中将这些值设置为零。即,我需要使用
T.set\u子传感器
。要使用它,我需要在
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)]
不起作用。

您需要使用与之不同的编号

这里有一个例子,可以满足您的需要

更新:现在可用于参数化轴,但请注意,
不能是符号

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

My
轴是可变的。而且
ndim
是可变的(在我的测试中是3)。那会是什么样子?@Albert更新了代码,但注释轴不能是符号。啊,我明白了,我也错过了
nonzero()
。我现在使用的是
tt.switch(mask,0,x)
而不是
tt.set\u子传感器(x[mask.nonzero()],0)
。你知道哪个更快吗?我不知道,但我也有兴趣知道。我希望优化器能够检测等价性并生成相同的执行图。另一个后续问题是:
mask.nonzero()
argm
之间有什么区别?