pytorch中的embedding詞向量的使用

Embedding

詞嵌入在 pytorch 中非常簡單,只需要調用 torch.nn.Embedding(m, n) 就可以了,m 表示單詞的總數目,n 表示詞嵌入的維度,其實詞嵌入就相當於是一個大矩陣,矩陣的每一行表示一個單詞。

emdedding初始化

默認是隨機初始化的

import torch
from torch import nn
from torch.autograd import Variable
# 定義詞嵌入
embeds = nn.Embedding(2, 5) # 2 個單詞,維度 5
# 得到詞嵌入矩陣,開始是隨機初始化的
torch.manual_seed(1)
embeds.weight
# 輸出結果:
Parameter containing:
-0.8923 -0.0583 -0.1955 -0.9656  0.4224
 0.2673 -0.4212 -0.5107 -1.5727 -0.1232
[torch.FloatTensor of size 2x5]

如果從使用已經訓練好的詞向量,則採用

pretrained_weight = np.array(args.pretrained_weight)  # 已有詞向量的numpy
self.embed.weight.data.copy_(torch.from_numpy(pretrained_weight))

embed的讀取

讀取一個向量。 
注意參數只能是LongTensor型的

# 訪問第 50 個詞的詞向量
embeds = nn.Embedding(100, 10)
embeds(Variable(torch.LongTensor([50])))
# 輸出:
Variable containing:
 0.6353  1.0526  1.2452 -1.8745 -0.1069  0.1979  0.4298 -0.3652 -0.7078  0.2642
[torch.FloatTensor of size 1x10]

讀取多個向量。 
輸入爲兩個維度(batch的大小,每個batch的單詞個數),輸出則在兩個維度上加上詞向量的大小。

見代碼

# an Embedding module containing 10 tensors of size 3
embedding = nn.Embedding(10, 3)
# 每批取兩組,每組四個單詞
input = Variable(torch.LongTensor([[1,2,4,5],[4,3,2,9]]))
a = embedding(input) # 輸出2*4*3
a[0],a[1]

輸出爲:

(Variable containing:
 -1.2603  0.4337  0.4181
  0.4458 -0.1987  0.4971
 -0.5783  1.3640  0.7588
  0.4956 -0.2379 -0.7678
 [torch.FloatTensor of size 4x3], Variable containing:
 -0.5783  1.3640  0.7588
 -0.5313 -0.3886 -0.6110
  0.4458 -0.1987  0.4971
 -1.3768  1.7323  0.4816
 [torch.FloatTensor of size 4x3])

轉自:https://blog.csdn.net/david0611/article/details/81090371

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章