PyTorch在NLP任務中使用預訓練詞向量

2021-09-26 22:46:47 字數 3531 閱讀 4939

在使用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()12

3456

78910

1112

1314

構建詞表,此過程也可使用keras或torchtext來簡化完成,完整**見文末倉庫。

from gensim.test.utils import datapath, get_tmpfile

from gensim.models import keyedvectors

# 已有的glove詞向量

glove_file = datapath('test_glove.txt')

# 指定轉化為word2vec格式後檔案的位置

tmp_file = get_tmpfile("test_word2vec.txt")

from gensim.scripts.glove2word2vec import glove2word2vec

glove2word2vec(glove_file, tmp_file)12

3456

78去詞向量檔案中查表,得到詞表中單詞對應的權重weight。在詞向量檔案中沒匹配到的單詞則繼續保留全0向量。

# 使用gensim載入word2vec詞向量

wvmodel = gensim.models.keyedvectors.load_word2vec_format('/users/wyw/documents/vectors/word2vec/word2vec.6b.100d.txt', binary=false, encoding='utf-8')

vocab_size = len(vocab) + 1

embed_size = 100

weight = torch.zeros(vocab_size, embed_size)

for i in range(len(wvmodel.index2word)):

try:

index = word_to_idx[wvmodel.index2word[i]]

except:

continue

weight[index, :] = torch.from_numpy(wvmodel.get_vector(

idx_to_word[word_to_idx[wvmodel.index2word[i]]]))12

3456

78910

1112

13得到weight權重後,即可在pytorch的embedding層中就可以指定預訓練的詞向量。

embedding = nn.embedding.from_pretrained(weight)

# requires_grad指定是否在訓練過程中對詞向量的權重進行微調

self.embedding.weight.requires_grad = true12

3完整**見我的github倉庫: 下的language-model.ipynb檔案

2.使用torchtext載入預訓練的詞向量

下面介紹如何在torchtext中使用預訓練的詞向量,進而傳送給神經網路模型進行訓練。關於torchtext更完整的用法見我另一篇部落格:torchtext用法示例及完整**

通過name引數可以指定預訓練的詞向量檔案所在的目錄

預設情況下預訓練詞向量檔案和快取檔案的目錄位置都為當前目錄下的 .vector_cache目錄,雖然通過name引數指定了預訓練詞向量檔案存在的目錄,但是因為快取檔案的目錄沒有特殊指定,此時在當前目錄下仍然需要存在 .vector_cache 目錄。

# 通過pytorch建立的embedding層

embedding = nn.embedding(2000, 256)

# 指定嵌入矩陣的初始權重

weight_matrix = text.vocab.vectors

embedding.weight.data.copy_(weight_matrix )12

345乙個比較完整的示例

import torch

from torchtext import data

from torchtext import datasets

from torchtext.vocab import glove

import numpy as np

def load_data(opt):

# use torchtext to load data, no need to download dataset

print("loading {} dataset".format(opt.dataset))

# set up fields

text = data.field(lower=true, include_lengths=true, batch_first=true, fix_length=opt.max_seq_len)

label = data.field(sequential=false)

# make splits for data

train, test = datasets.imdb.splits(text, label)

# build the vocabulary

text.build_vocab(train, vectors=glove(name='6b', dim=300))

label.build_vocab(train)

在Pytorch中使用tensorboard

在pytorch中使用tensorboard的方法也挺簡單,如果要看網路結構和訓練損失的話基本上和在tf中使用是差不多的。import torch.nn as nn import torch.nn.functional as f import torch.optim as optim import ...

NLP預備任務

由於之前已經安裝好了tensorflow,所以就直接跳過這步了。參考 tensorflow安裝教程 tensrflow基礎 關注圖 會話 tensor 變數 feed和fetch。使用圖 graphs 來表示計算任務 在被稱之為會話 session 的上下文 context 中執行圖 使用tenso...

在PyTorch中使用Visdom視覺化工具

在pytorch中使用visdom視覺化工具 非常詳細 參考鏈結二 1.安裝 pip install visdom conda install visdom 2.linux 伺服器端 啟動 模型訓練前 預設使用埠 8097 to view training results and loss plot...