我有一个 theano 张量 A,使得 A.shape = (40, 20, 5) 和一个 theano 矩阵 B,使得 B.shape = (40, 20)。是否可以执行单行操作来获取矩阵 C,其中 C.shape = (40, 20) 和 C(i,j) = A[i, j, B[i,j]] 使用 theano 语法?
本质上,我想用B作为索引矩阵;使用 theano 执行此操作最有效/最优雅的方法是什么?
最佳答案
您可以在 numpy 中执行以下操作:
import numpy as np
A = np.arange(4 * 2 * 5).reshape(4, 2, 5)
B = np.arange(4 * 2).reshape(4, 2) % 5
C = A[np.arange(A.shape[0])[:, np.newaxis], np.arange(A.shape[1]), B]
所以你可以在 theano 中做同样的事情:
import theano
import theano.tensor as T
AA = T.tensor3()
BB = T.imatrix()
CC = AA[T.arange(AA.shape[0]).reshape((-1, 1)), T.arange(AA.shape[1]), BB]
f = theano.function([AA, BB], CC)
f(A.astype(theano.config.floatX), B)
关于python - theano 中用索引矩阵索引张量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33947726/