gpt4 book ai didi

arrays - Theano张量切片...如何使用 bool 值切片?

转载 作者:行者123 更新时间:2023-12-04 02:07:14 26 4
gpt4 key购买 nike

在 numpy 中,如果我有一个 bool 数组,我可以用它来选择另一个数组的元素:

>>> 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 函数声明中正确实例化“给定”参数。提前致谢。

最佳答案

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

关于arrays - Theano张量切片...如何使用 bool 值切片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37425401/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com