【发布时间】:2019-12-29 02:53:56
【问题描述】:
我目前正在尝试使用 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 嵌入层的正确方法是什么?
【问题讨论】: