Theano张量切片...如何使用布尔切片? [英] Theano tensor slicing... how to use boolean to slice?
问题描述
在numpy中,如果我有一个布尔数组,则可以使用它来选择另一个数组的元素:
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])
我需要这样做在theano。这是我尝试的方法,但是得到了意外的结果。
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.])
有人可以解释theano结果并建议如何获得numpy结果吗?我需要知道如何执行此操作才能正确实例化theano函数声明中的给定参数。
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.
推荐答案
这是在theano中不受支持:
我们不支持布尔值掩码,因为Theano没有布尔类型(我们将int8用于逻辑运算符的输出)。
We do not support boolean masks, as Theano does not have a boolean type (we use int8 for the output of logic operators).
Theano带有掩码的索引(错误的方法):
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)
...
获得Theano结果,例如NumPy:
Getting a Theano result like NumPy:
>>> t[(t > 4).nonzero()].eval()
array([5, 6, 7, 8])
所以您需要 y = x [idx.nonzero()]
这篇关于Theano张量切片...如何使用布尔切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!