首页 文章

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

提问于
浏览
1

假设我有一个索引矩阵:

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

嵌入矩阵:

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

index_matrix 中的每个元素对应于 embeddings_matrix 中的一个特定行 . 例如, index_matrix 中的 0 对应于 embeddings_matrix 中的 [1,2,3] .

仅使用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案例上 .

1 回答

  • 1

    您可以使用索引矩阵简单地索引到嵌入矩阵:

    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,索引矩阵中的每个元素根据需要用相应的嵌入向量替换 .

相关问题