问题
In numpy, if I have a boolean array, I can use it to select elements of another array:
>>> import numpy as np
>>> x = np.array([1, 2, 3])
>>> idx = np.array([True, False, True])
>>> x[idx]
array([1, 3])
I need to do this in theano. This is what I tried, but I got an unexpected result.
>>> 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.])
Can someone explain the theano result and suggest how to get the numpy result? I need to know how to do this in order to properly instantiate a 'givens' argument in a theano function declaration. Thanks in advance.
回答1:
This is not supported in 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])
So you need y = x[idx.nonzero()]
来源:https://stackoverflow.com/questions/37425401/theano-tensor-slicing-how-to-use-boolean-to-slice