theano 在第二个张量中找到张量元素的索引

theano finding the indices of a tensor elements in a second tensor

我似乎找不到解决方案。给定两个 theano 张量 a 和 b,我想在张量 a 中找到 b 中元素的索引。这个例子会有所帮助,比如 a = [1, 5, 10, 17, 23, 39] 和 b = [1, 10, 39],我希望结果是张量 a 中 b 值的索引,即 [ 0, 2, 5].

花了一些时间,我认为最好的方法是使用扫描;这是我拍摄的最小示例。

def getIndices(b_i, b_v, ar):
    pI_subtensor = pI[b_i]
    return T.set_subtensor(pI_subtensor, np.where(ar == b_v)[0])

ar = T.ivector()
b = T.ivector()
pI = T.zeros_like(b)

result, updates = theano.scan(fn=getIndices,
                              outputs_info=None,
                              sequences=[T.arange(b.shape[0], dtype='int32'), b],
                              non_sequences=ar)

get_proposal_indices = theano.function([b, ar], outputs=result)

d = get_proposal_indices( np.asarray([1, 10, 39], dtype=np.int32), np.asarray([1, 5, 10, 17, 23, 39], dtype=np.int32) )

我收到错误:

TypeError: Trying to increment a 0-dimensional subtensor with a 1-dimensional value.

在 return 语句行中。此外,输出需要是形状为 b 的单个张量,我不确定这是否会得到所需的结果。任何建议都会有所帮助。

这完全取决于您的阵列有多大。只要它适合内存,你就可以进行如下操作

import numpy as np
import theano
import theano.tensor as T

aa = T.ivector()
bb = T.ivector()

equality = T.eq(aa, bb[:, np.newaxis])
indices = equality.nonzero()[1]

f = theano.function([aa, bb], indices)

a = np.array([1, 5, 10, 17, 23, 39], dtype=np.int32)
b = np.array([1, 10, 39], dtype=np.int32)

f(a, b)

# outputs [0, 2, 5]