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

3
在numpy中,如果我有一个布尔数组,我可以使用它来选择另一个数组的元素:
>>> 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”参数。提前感谢。


1
你得到了 [2, 1, 2],因为 [True, False, True] 被解释为 [0, 1, 0] - Eric
1
谢谢!我明白你的意思:[True, False, True] 的计算结果是 [1,0,1]。你知道如何让它计算出 numpy 的结果吗?有没有办法像 numpy 一样进行布尔切片操作? - matlibplotter
哎呀,我的意思是这个,0和1的位置搞反了。请看我的答案。 - Eric
1个回答

5
这在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()]


谢谢!这正是我在寻找的。=) - matlibplotter
为此卡了好几个小时,非常感谢。Theano文档中关于T.nonzero这里简直是空的 - user27886
@user27886:T.nonzeronp.nonzero()相同,已有文档记录。 - Eric
而numpy文档中的高级索引解释了布尔索引如何转换为.nonzero - Eric
@Eric,你知道我怎么找到实现整数数组索引的Theano源代码吗?我特别感兴趣的是GPU数组索引支持(可能是CUDA代码)。 - zwlayer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接