Embedding模块 from_pretrained 加载预训练好的词向量

Embedding 模块作用:将词的索引转化为词对应的词向量,需要我们设置的两个参数:词汇表的大小和词嵌入的维度。
num_embeddings (int): size of the dictionary of embeddings
embedding_dim (int): the size of each embedding vector
>>> # an Embedding module containing 10 tensors of size 3
#词汇表里有10个词,每个词向量嵌入维度是3
>>> embedding = nn.Embedding(10, 3)

注意:输入不是单词,而是要处理成 单词对应的索引,我们用个字典来存储 单词到索引的字典

word_to_idx={}
word_to_idx={word:i for i,word in enumerate(vocab)}

再把 索引封装成 向量形式

hello_to_tensor = torch.tensor([word_to_ix["hello"]], dtype=torch.long)

就可以送进上面定义好的embedding了,

hello_embed = embedding(hello_to_tensor)

 from_pretrained 加载预训练好的词向量

  我们在进行具体nlp任务时,一般通过对应的Embedding层做词向量的处理,再拿词向量去进行下游的处理,比如分类啥的,但我们可以使用预训练好的词向量, 比如使用gensim训练好的word2vec词向量,会带来更优的性能。有一点需要注意的是 ,当我们将genism已经训练好的词向量作为自己初始化的词向量,我们可以设置 词向量 是否还有随下游任务进行变动这个参数默认是 将词向量冻结住。

>>> weight = torch.FloatTensor([[1, 2.3, 3], [4, 5.1, 6.3]])
>>> embedding = nn.Embedding.from_pretrained(weight)
>>> # Get embeddings for index 1
>>> input = torch.LongTensor([1])
>>> embedding(input)

 tensor([[ 4.0000,  5.1000,  6.3000]])

 



posted @ 2020-12-09 16:40  打了鸡血的女汉子  阅读(6856)  评论(1编辑  收藏  举报