假设我有一个索引矩阵:
index_matrix = [[0,1],
[2,1]]
还有一个嵌入矩阵:
embeddings_matrix = [[1,2,3],
[2,3,4],
[4,5,6],
.
.
. ]
index_matrix
中的每个元素对应于 embeddings_matrix
中的特定行。例如,0
在 index_matrix
对应[1,2,3]
在 embeddings_matrix
.
仅使用 theano 语法,如何构建 3D 张量,其中 index_matrix
中的每个索引被替换为 embeddings_matrix
中的行或向量?
编辑:我能够解决类似的问题:使用 index_vector = [0,1,2,1]
的问题和 embeddings_matrix
上面生成一个 2D 张量。为此,我需要以下 theano 语法:
Matrix = embeddings_matrix[index_vector].reshape((index_vector.shape[0], -1))
但是,我对 3D 案例有点困惑。
最佳答案
您可以简单地使用索引矩阵对嵌入矩阵进行索引:
import numpy
import theano
import theano.tensor as tt
embeddings_matrix = theano.shared(numpy.array([[1, 2, 3], [2, 3, 4], [4, 5, 6]], dtype=theano.config.floatX))
index_matrix = tt.imatrix()
y = embeddings_matrix[index_matrix]
f = theano.function([index_matrix], y)
output = f(numpy.array([[0, 1], [2, 1]], dtype=numpy.int32))
print output.shape, '\n', output
这会打印
(2L, 2L, 3L)
[[[ 1. 2. 3.]
[ 2. 3. 4.]]
[[ 4. 5. 6.]
[ 2. 3. 4.]]]
输出是 3D 的,索引矩阵中的每个元素根据需要替换为相应的嵌入向量。
关于python - theano ~ 使用索引矩阵和嵌入矩阵来生成 3D 张量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33879775/