首页 > 解决方案 > 将 OHE 查找表用于 pytorch RNN 的正确方法是什么?

问题描述

我目前正在尝试使用 pytorch 构建 LSTM RNN。一个输入向量表示为一个由 50 个整数组成的数组,对应于最多 50 个带有填充的标记的序列,其中每个整数对应于我的词汇表中的一个元素和 OHE 向量中 1 的索引。我想要一个嵌入层,它只使用一个查找表来对整数进行 One-hot 编码——有点像 tensorflow 的 OHE 层。

像这种“类型”的作品

import torch
import numpy as np
import torch.nn as nn 

# vocab_size is the number of words in your train, val and test set
# vector_size is the dimension of the word vectors you are using
vocab_size, vector_size = 5, 5
embed = nn.Embedding(vocab_size, vector_size)

# intialize the word vectors, pretrained_weights is a 
# numpy array of size (vocab_size, vector_size) and 
# pretrained_weights[i] retrieves the word vector of
# i-th word in the vocabulary
pretrained_weights = np.zeros((vocab_size, vector_size))
np.fill_diagonal(pretrained_weights, 1)
tmp =torch.from_numpy(pretrained_weights)
embed.weight = nn.Parameter(tmp,requires_grad=False )

# Then turn the word index into actual word vector
vocab = {"some": 0, "words": 1}
word_indexes = torch.from_numpy(np.array([vocab[w] for w in ["some", "words"]]))
word_vectors = embed(word_indexes)
word_vectors.data.numpy()


>>>output
array([[1., 0., 0., 0., 0.],
       [0., 1., 0., 0., 0.]])

但它非常hacky,并且不能很好地处理成批的输入向量。

在 RNN 开始时声明 OHE 嵌入层的正确方法是什么?

标签: pythonnlppytorchlstm

解决方案


您正在寻找的方法是torch.nn.functional.one_hot. 它后来被添加到 PyTorch 中,所以当你用谷歌搜索它时很难找到它。

 >>> import torch
>>> x = torch.arange(0,5)
>>> x
tensor([0, 1, 2, 3, 4])
>>> torch.nn.functional.one_hot(x)
tensor([[1, 0, 0, 0, 0],
      [0, 1, 0, 0, 0],
      [0, 0, 1, 0, 0],
      [0, 0, 0, 1, 0],
      [0, 0, 0, 0, 1]])

推荐阅读