Theano张量切片...如何使用布尔值切片?

Theano tensor slicing... how to use boolean to slice?

在 numpy 中,如果我有一个布尔数组,我可以将它用于 select 另一个数组的元素:

>>> import numpy as np
>>> x = np.array([1, 2, 3])
>>> idx = np.array([True, False, True])
>>> x[idx] 
array([1, 3])

我需要在 theano 中执行此操作。这是我尝试过的,但我得到了意想不到的结果。

>>> from theano import tensor as T
>>> x = T.vector()
>>> idx = T.ivector()
>>> y = x[idx]
>>> y.eval({x: np.array([1,2,3]), idx: np.array([True, False, True])})
array([ 2.,  1.,  2.])

谁能解释一下theano的结果并建议如何得到numpy的结果?我需要知道如何执行此操作,以便在 theano 函数声明中正确实例化 'givens' 参数。提前致谢。

这是not supported在theano中:

We do not support boolean masks, as Theano does not have a boolean type (we use int8 for the output of logic operators).

Theano indexing with a “mask” (incorrect approach):

>>> t = theano.tensor.arange(9).reshape((3,3))
>>> t[t > 4].eval()  # an array with shape (3, 3, 3)
...

Getting a Theano result like NumPy:

>>> t[(t > 4).nonzero()].eval()
array([5, 6, 7, 8])

所以你需要y = x[idx.nonzero()]