深度学习之Embedding

在深度学习模型中,Embedding层在代码层面上的意义是:一个保存了固定字典和大小的简单查找表。这个模块常用来保存词嵌入和用下标检索它们。模块的输入是一个下标的列表,输出是对应的词嵌入。

当输入是一个batch时,则这个输入矩阵是一个N维矩阵([batch_size,Seq_len]),输出矩阵([batch_size,Seq_len,embed_size])

PyTorch:

import torch
from torch import nn
from torch.autograd import Variable

embeds = nn.Embedding(20,5)
word_to_ix = {}
for i in range(20):
    word_to_ix[i] = i+1

hello_idx = torch.LongTensor([[3,6],[8,9]])
hello_idx = Variable(hello_idx)

embeds(hello_idx)

tensor([[[-0.7695,  0.1445, -0.7704, -0.6968,  0.1774],
         [-0.5415,  0.2232, -0.3729,  1.5091,  1.5055]],

        [[ 0.2723,  0.5890,  0.3809,  2.1650,  1.0792],
         [ 0.6174,  0.3788,  1.3872,  0.4625,  0.4803]]],
       grad_fn=<EmbeddingBackward>)


hello_idx = torch.LongTensor([[2,4]])
hello_idx = Variable(hello_idx)

embeds(hello_idx)

tensor([[[-0.7695,  0.1445, -0.7704, -0.6968,  0.1774],
         [-0.5415,  0.2232, -0.3729,  1.5091,  1.5055]]],
       grad_fn=<EmbeddingBackward>)

TensorFlow:

tf.nn.embedding_lookup()就是根据input_ids中的id,寻找embeddings中的第id行。比如input_ids=[1,3,5],则找出embeddings中第1,3,5行,组成一个tensor返回。

embedded_words = tf.nn.embedding_lookup(embedding_w, self.inputs)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值