在Pytorch中嵌入3D数据

时间:2017-11-09 15:33:14

标签: nlp pytorch

我想实现字符级嵌入。

这是通常的单词嵌入。

Word嵌入

Input: [ [‘who’, ‘is’, ‘this’] ] 
-> [ [3, 8, 2] ]     # (batch_size, sentence_len)
-> // Embedding(Input)
 # (batch_size, seq_len, embedding_dim)

这就是我想要做的。

字符嵌入

Input: [ [ [‘w’, ‘h’, ‘o’, 0], [‘i’, ‘s’, 0, 0], [‘t’, ‘h’, ‘i’, ‘s’] ] ]
-> [ [ [2, 3, 9, 0], [ 11, 4, 0, 0], [21, 10, 8, 9] ] ]      # (batch_size, sentence_len, word_len)
-> // Embedding(Input) # (batch_size, sentence_len, word_len, embedding_dim)
-> // sum each character embeddings  # (batch_size, sentence_len, embedding_dim)
The final output shape is same as Word embedding. Because I want to concat them later.

虽然我尝试过,但我不确定如何实现3-D嵌入。你知道如何实现这样的数据吗?

def forward(self, x):
    print('x', x.size()) # (N, seq_len, word_len)
    bs = x.size(0)
    seq_len = x.size(1)
    word_len = x.size(2)
    embd_list = []
    for i, elm in enumerate(x):
        tmp = torch.zeros(1, word_len, self.embd_size)
        for chars in elm:
            tmp = torch.add(tmp, 1.0, self.embedding(chars.unsqueeze(0)))

上面的代码出错了,因为self.embedding的输出是Variable

TypeError: torch.add received an invalid combination of arguments - got (torch.FloatTensor, float, Variable), but expected one of:
 * (torch.FloatTensor source, float value)
 * (torch.FloatTensor source, torch.FloatTensor other)
 * (torch.FloatTensor source, torch.SparseFloatTensor other)
 * (torch.FloatTensor source, float value, torch.FloatTensor other)
      didn't match because some of the arguments have invalid types: (torch.FloatTensor, float, Variable)
 * (torch.FloatTensor source, float value, torch.SparseFloatTensor other)
      didn't match because some of the arguments have invalid types: (torch.FloatTensor, float, Variable)

更新

我能做到这一点。但是for对批处理无效。你们知道更有效率的方式吗?

def forward(self, x):
    print('x', x.size()) # (N, seq_len, word_len)
    bs = x.size(0)
    seq_len = x.size(1)
    word_len = x.size(2)
    embd = Variable(torch.zeros(bs, seq_len, self.embd_size))
    for i, elm in enumerate(x): # every sample
        for j, chars in enumerate(elm): # every sentence. [ [‘w’, ‘h’, ‘o’, 0], [‘i’, ‘s’, 0, 0], [‘t’, ‘h’, ‘i’, ‘s’] ]
            chars_embd = self.embedding(chars.unsqueeze(0)) # (N, word_len, embd_size) [‘w’,‘h’,‘o’,0]
            chars_embd = torch.sum(chars_embd, 1) # (N, embd_size). sum each char's embedding
            embd[i,j] = chars_embd[0] # set char_embd as word-like embedding

    x = embd # (N, seq_len, embd_dim)

UPDATE2

这是我的最终代码。谢谢,瓦斯艾哈迈德!

def forward(self, x):
    # x: (N, seq_len, word_len)
    input_shape = x.size()
    bs = x.size(0)
    seq_len = x.size(1)
    word_len = x.size(2)
    x = x.view(-1, word_len) # (N*seq_len, word_len)
    x = self.embedding(x) # (N*seq_len, word_len, embd_size)
    x = x.view(*input_shape, -1) # (N, seq_len, word_len, embd_size)
    x = x.sum(2) # (N, seq_len, embd_size)

    return x

1 个答案:

答案 0 :(得分:8)

我假设你有一个3d张量的形状BxSxW,其中:

B = Batch size
S = Sentence length
W = Word length

您已声明嵌入图层如下。

self.embedding = nn.Embedding(dict_size, emsize)

其中:

dict_size = No. of unique characters in the training corpus
emsize = Expected size of embeddings

所以,现在你需要将形状BxSxW的三维张量转换为形状BSxW的二维张量并将其赋予嵌入层。

emb = self.embedding(input_rep.view(-1, input_rep.size(2)))

emb的形状为BSxWxE,其中E是嵌入大小。您可以将生成的3d张量转换为4d张量,如下所示。

emb = emb.view(*input_rep.size(), -1)

emb的最终形状为BxSxWxE,这正是您所期望的。