numpy - argmax 结果作为子张量

标签 numpy theano

我想使用保留尺寸的 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/

相关文章:

python - Keras 段错误(核心已转储)

python - Keras 均方误差损失层

python - Theano 步骤给出 File in wrong format 错误

python - 用numba计算内积的正确方法

python - 将 Numpy 数组转换为 Pandas DataFrame

python - python 中的冒号放在数组后面有什么作用?

python - 如何调试 theano 张量的形状不匹配?

python - 为什么floatX的标志会影响Theano中是否使用GPU?

python - 设置为 numpy 数组切片时如何禁用大小更改广播?

python - numpy 矩阵向量乘法