python - theano ~ 使用索引矩阵和嵌入矩阵来生成 3D 张量?

标签 python matrix theano

假设我有一个索引矩阵:

index_matrix = [[0,1],
                [2,1]]

还有一个嵌入矩阵:

embeddings_matrix = [[1,2,3],
                     [2,3,4],
                     [4,5,6],
                        .
                        .
                        .   ]

index_matrix 中的每个元素对应于 embeddings_matrix 中的特定行。例如,0index_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/

相关文章:

python - 如何在 Python 中删除文件

c++ - 如何在 OpenGL 中正确旋转和缩放对象?

python - 更新 theano 函数中的参数

gpu - 将 GPU 用作视频卡和 GPGPU

python - 更快的 App Engine 开发数据存储替代方案

使用 cx_Freeze 构建的 Python 可执行文件崩溃

c - 矩阵乘法控制

python - 做点积时的 NumPy 精度

python - 导入Python模块可以在解释器中工作,但不能在脚本中工作

使用指针将浮点矩阵复制并转换为 double 矩阵