TensorFlow中embedding_lookup()函数的意义,查表中的矩阵如何得到

1.embedding_lookup()函数

调用参数

tf.nn.embedding_lookup(params, ids, partition_strategy='mod', name=None)

params参数:可以是一个二位矩阵,也可以是张量的列表,在这种情况下,ids表示多个张量的索引组合。例如,给定ids[0, 3][1, 4][2, 5],得到的张量都是[2, 64]的列表。

ids参数:按照ids从params中检索对应的行。

partition_strategy参数:可以控制ids在列表中的分配方式。当矩阵可能太大而无法合为一体时,分区策略对于较大规模的问题很有用,例如(假设您在tf.InteractiveSession()内),将返回[10 20 30 40],因为params的第一个元素(索引0)是10,params的第二个元素(索引1)是20,依此类推。

params = tf.constant([10,20,30,40])
ids = tf.constant([0,1,2,3])
print tf.nn.embedding_lookup(params,ids).eval()

功能:实现将id特征映射成一个低维稠密向量

embedding_lookup函数检索params张量的行。该行为类似于对numpy中的数组使用索引。例如:

matrix = np.random.random([1024, 64])  # 64-dimensional embeddings
ids = np.array([0, 5, 17, 33])
print matrix[ids]  # prints a matrix of shape [4, 64]

2.embedding_lookup()函数中的输入矩阵如何得到?

embedding_lookup理论上就是用矩阵相乘实现的,就可以看成一个特殊的“全连接层”

假设embedding权重矩阵是一个[vocab_size, embed_size]的稠密矩阵W,vocab_size是需要embed的所有item的个数(比如:所有词的个数,所有商品的个数),embed_size是映射后的向量长度。

所谓embedding_lookup(W, id1),可以想像成一个只在id1位为1的[1, vocab_size]的one_hot向量,与[vocab_size, embed_size]的W矩阵相乘,结果是一个[1, embed_size]的向量,它就是id1对应的embedding向量,实际上就是W矩阵的第id1行

以上过程只是前代,因为W一般是随机初始化的,是待优化的变量。因此,embedding_lookup除了要完成以上矩阵相乘的过程(实现成“抽取id对应的行”),还要完成自动求导,以实现对W的更新。

    def forward(self, X):
        """
        :param X: SparseInput
        :return: [batch_size, embed_size]
        """
        self._last_input = X

        # output: [batch_size, embed_size]
        output = np.zeros((X.n_total_examples, self._W.shape[1]))

        for example_idx, feat_id, feat_val in X.iterate_non_zeros():
            embedding = self._W[feat_id, :]
            output[example_idx, :] += embedding * feat_val

        return output

    def backward(self, prev_grads):
        """
        :param prev_grads: [batch_size, embed_size]
        :return: dw
        """
        dW = {}

        for example_idx, feat_id, feat_val in self._last_input.iterate_non_zeros():
            # [1,embed_size]
            grad_from_one_example = prev_grads[example_idx, :] * feat_val

            if feat_id in dW:
                dW[feat_id] += grad_from_one_example

            else:
                dW[feat_id] = grad_from_one_example

        return dW

参考:

1.https://www.zhihu.com/question/48107602?sort=created

2.github中embedinglayer的实现:https://github.com/stasi009/NumpyWDL/blob/master/embedding_layer.py

3.TensorFlow中文社区文档:http://www.tensorfly.cn/tfdoc/api_docs/python/nn.html#embedding_lookup

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章