pytorch中的embedding詞向量的使用方法
Embedding
詞嵌入在 pytorch 中非常簡(jiǎn)單,只需要調(diào)用 torch.nn.Embedding(m, n) 就可以了,m 表示單詞的總數(shù)目,n 表示詞嵌入的維度,其實(shí)詞嵌入就相當(dāng)于是一個(gè)大矩陣,矩陣的每一行表示一個(gè)單詞。
emdedding初始化
默認(rèn)是隨機(jī)初始化的
import torch from torch import nn from torch.autograd import Variable # 定義詞嵌入 embeds = nn.Embedding(2, 5) # 2 個(gè)單詞,維度 5 # 得到詞嵌入矩陣,開始是隨機(jī)初始化的 torch.manual_seed(1) embeds.weight # 輸出結(jié)果: 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]
如果從使用已經(jīng)訓(xùn)練好的詞向量,則采用
pretrained_weight = np.array(args.pretrained_weight) # 已有詞向量的numpy self.embed.weight.data.copy_(torch.from_numpy(pretrained_weight))
embed的讀取
讀取一個(gè)向量。
注意參數(shù)只能是LongTensor型的
# 訪問第 50 個(gè)詞的詞向量 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]
讀取多個(gè)向量。
輸入為兩個(gè)維度(batch的大小,每個(gè)batch的單詞個(gè)數(shù)),輸出則在兩個(gè)維度上加上詞向量的大小。
Input: LongTensor (N, W), N = mini-batch, W = number of indices to extract per mini-batch Output: (N, W, embedding_dim)
見代碼
# an Embedding module containing 10 tensors of size 3 embedding = nn.Embedding(10, 3) # 每批取兩組,每組四個(gè)單詞 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])
以上這篇pytorch中的embedding詞向量的使用方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
使用PM2+nginx部署python項(xiàng)目的方法示例
這篇文章主要介紹了使用PM2+nginx部署python項(xiàng)目的方法示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-11-11Python?中給請(qǐng)求設(shè)置用戶代理?User-Agent的方法
本文介紹?HTTP?標(biāo)頭用戶代理主題以及如何使用?Python?中的請(qǐng)求設(shè)置用戶代理,您將了解?HTTP?標(biāo)頭及其在理解用戶代理、獲取用戶代理以及學(xué)習(xí)使用?Python?中的請(qǐng)求設(shè)置用戶代理的多種方法方面的重要性,感興趣的朋友跟隨小編一起看看吧2023-06-06Python 帶你快速上手 Apache APISIX 插件開發(fā)
Apache APISIX Python Runner 來了,社區(qū)中的小伙伴們?cè)陂_發(fā) Apache APISIX 插件時(shí)又多了一種新選擇,本文將用實(shí)列向大家介紹,需要的朋友可以參考下面文章內(nèi)容2021-09-09深入理解python?生成器、迭代器、動(dòng)態(tài)新增屬性及方法
這篇文章主要介紹了python?生成器、迭代器、動(dòng)態(tài)新增屬性及方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-04-04python調(diào)用staf自動(dòng)化框架的方法
今天小編就為大家分享一篇python調(diào)用staf自動(dòng)化框架的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-12-12python實(shí)現(xiàn)處理Excel表格超詳細(xì)系列
這篇文章主要介紹了python實(shí)現(xiàn)處理Excel表格超詳細(xì)系列,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-08-08