PyTorch在NLP任务中使用预训练词向量

在使用pytorch或tensorflow等神经网络框架进行nlp任务的处理时,可以通过对应的Embedding层做词向量的处理,更多的时候,使用预训练好的词向量会带来更优的性能。下面分别介绍使用gensim和torchtext两种加载预训练词向量的方法。

1.使用gensim加载预训练词向量

    对于如下这样一段语料

test_sentence = """When forty winters shall besiege thy brow,
And dig deep trenches in thy beauty's field,
Thy youth's proud livery so gazed on now,
Will be a totter'd weed of small worth held:
Then being asked, where all thy beauty lies,
Where all the treasure of thy lusty days;
To say, within thine own deep sunken eyes,
Were an all-eating shame, and thriftless praise.
How much more praise deserv'd thy beauty's use,
If thou couldst answer 'This fair child of mine
Shall sum my count, and make my old excuse,'
Proving his beauty by succession thine!
This were to be new made when thou art old,
And see thy blood warm when thou feel'st it cold.""".split()

    构建词表,此过程也可使用Keras或torchtext来简化完成,完整代码见文末仓库。

# 给每个单词编码,也就是用数字来表示每个单词,这样才能够传入word embeding得到词向量。
vocab = set(test_sentence) # 通过set将重复的单词去掉
word_to_idx = {
   
   word: i+1 for i, word in enumerate(vocab)}
# 定义了一个unknown的词,也就是说没有出现在训练集里的词,我们都叫做unknown,词向量就定义为0。
word_to_idx['<unk>'] = 0
idx_to_word = {
   
   i+1: word for i, word in enumerate(vocab)}
idx_to_word[0] = '<unk>'

    使用gensim加载已训练好的word2vec词向量,此处用的是glove已训练好的词向量,下载链接:https://pan.baidu.com/s/1i5XmTA9 因为glove词向量和word2vec词向量格式略有不同,先使用gensim的scripts.glove2word2vec方法将glove词向量转化为word2vec词向量的格式。转化方式很简单,如下:

from gensim.test.utils import datapath, get_tmpfile
from gensim.</
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值