好久沒有寫博客了,這一次就將最近看的pytorch 教程中的lstm+crf的一些心得與困惑記錄下來。
原文 PyTorch Tutorials
參考了很多其他大神的博客,https://blog.csdn.net/cuihuijun1hao/article/details/79405740
https://www.jianshu.com/p/97cb3b6db573
至於原理,非常建議讀這篇英文博客,寫的非常非常非常好!!!!!!值得打印出來細細品讀!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!https://createmomo.github.io/2017/09/12/CRF_Layer_on_the_Top_of_BiLSTM_1/
https://createmomo.github.io/2017/09/12/CRF_Layer_on_the_Top_of_BiLSTM_1/
在這位大神的基礎上,根據自己的debug又添加了一些注釋pytorch版的bilstm+crf實現sequence label
為了方便理解:
注意,
self.transitions = nn.Parameter(torch.randn(self.tagset_size, self.tagset_size)) 說明了轉移矩陣是隨機的!!!隨機的!!!隨機的!!!,而且放入了網絡中,會更新的!!!會更新的!!!會更新的!!!
解釋一下重點的函數功能:
def log_sum_exp(vec) 這個函數,是一個封裝好的數學公式,里面先做減法的原因在於,減去最大值可以避免e的指數次,計算機上溢。
def _forward_alg(self, feats): 這個函數,只是根據 隨機的transitions ,前向傳播算出的一個score,用到了動態規划的思想,但是因為用的是隨機的轉移矩陣,算出的值很大 score>20
def _get_lstm_features(self, sentence): 可以看出,函數里經過了embedding,lstm,linear層,是根據LSTM算出的一個矩陣。這里是11x5的一個tensor,而這個11x5的tensor,就是發射矩陣!!!發射矩陣!!!發射矩陣!!!(emission matrix)
def _score_sentence(self, feats, tags):是根據真實的標簽算出的一個score,這與上面的def _forward_alg(self, feats)有什么不同的地方嘛?共同之處在於,兩者都是用的隨機的轉移矩陣算的score,但是不同地方在於,上面那個函數算了一個最大可能路徑,但是實際上可能不是真實的 各個標簽轉移的值。例如說,真實的標簽 是 N V V,但是因為transitions是隨機的,所以上面的函數得到的其實是N N N這樣,兩者之間的score就有了差距。而后來的反向傳播,就能夠更新transitions,使得轉移矩陣逼近真實的“轉移矩陣”。(個人理解)
def _viterbi_decode(self, feats):維特比解碼,實際上就是在預測的時候使用了,輸出得分與路徑值。
這個函數是重點:
def neg_log_likelihood(self, sentence, tags):
feats = self._get_lstm_features(sentence)#11*5 經過了LSTM+Linear矩陣后的輸出,之后作為CRF的輸入。
forward_score = self._forward_alg(feats) #0維的一個得分,20.*來着
gold_score = self._score_sentence(feats, tags)#tensor([ 4.5836])
return forward_score - gold_score #這是兩者之間的差值,后來直接根據這個差值,反向傳播。。。神奇!!!!!!
def forward(self, sentence):forward函數只是用來預測了,train的時候沒用調用它,這讓我感到很震驚,還有這種操作?
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.optim as optim
def to_scalar(var): #var是Variable,維度是1
# returns a python float
return var.view(-1).data.tolist()[0]
def argmax(vec):
# return the argmax as a python int
_, idx = torch.max(vec, 1)
return to_scalar(idx)
def prepare_sequence(seq, to_ix):
idxs = [to_ix[w] for w in seq]
tensor = torch.LongTensor(idxs)
return autograd.Variable(tensor)
# Compute log sum exp in a numerically stable way for the forward algorithm
def log_sum_exp(vec): #vec是1*5, type是Variable
max_score = vec[0, argmax(vec)]
#max_score維度是1, max_score.view(1,-1)維度是1*1,max_score.view(1, -1).expand(1, vec.size()[1])的維度是1*5
max_score_broadcast = max_score.view(1, -1).expand(1, vec.size()[1]) # vec.size()維度是1*5
return max_score + torch.log(torch.sum(torch.exp(vec - max_score_broadcast)))#為什么指數之后再求和,而后才log呢
class BiLSTM_CRF(nn.Module):
def __init__(self, vocab_size, tag_to_ix, embedding_dim, hidden_dim):
super(BiLSTM_CRF, self).__init__()
self.embedding_dim = embedding_dim
self.hidden_dim = hidden_dim
self.vocab_size = vocab_size
self.tag_to_ix = tag_to_ix
self.tagset_size = len(tag_to_ix)
self.word_embeds = nn.Embedding(vocab_size, embedding_dim)
self.lstm = nn.LSTM(embedding_dim, hidden_dim // 2, num_layers=1, bidirectional=True)
# Maps the output of the LSTM into tag space.
self.hidden2tag = nn.Linear(hidden_dim, self.tagset_size)
# Matrix of transition parameters. Entry i,j is the score of
# transitioning *to* i *from* j. 居然是隨機初始化的!!!!!!!!!!!!!!!之后的使用也是用這隨機初始化的值進行操作!!
self.transitions = nn.Parameter(torch.randn(self.tagset_size, self.tagset_size))
# These two statements enforce the constraint that we never transfer
# to the start tag and we never transfer from the stop tag
self.transitions.data[tag_to_ix[START_TAG], :] = -10000
self.transitions.data[:, tag_to_ix[STOP_TAG]] = -10000
self.hidden = self.init_hidden()
def init_hidden(self):
return (autograd.Variable(torch.randn(2, 1, self.hidden_dim // 2)),
autograd.Variable(torch.randn(2, 1, self.hidden_dim // 2)))
#預測序列的得分
def _forward_alg(self, feats):
# Do the forward algorithm to compute the partition function
init_alphas = torch.Tensor(1, self.tagset_size).fill_(-10000.) #1*5 而且全是-10000
# START_TAG has all of the score.
init_alphas[0][self.tag_to_ix[START_TAG]] = 0. #因為start tag是4,所以tensor([[-10000., -10000., -10000., 0., -10000.]]),將start的值為零,表示開始進行網絡的傳播,
# Wrap in a variable so that we will get automatic backprop
forward_var = autograd.Variable(init_alphas) #初始狀態的forward_var,隨着step t變化
# Iterate through the sentence 會迭代feats的行數次,
for feat in feats: #feat的維度是5 依次把每一行取出來~
alphas_t = [] # The forward variables at this timestep
for next_tag in range(self.tagset_size):#next tag 就是簡單 i,從0到len
# broadcast the emission score: it is the same regardless of
# the previous tag
emit_score = feat[next_tag].view(1, -1).expand(1, self.tagset_size) #維度是1*5 噢噢!原來,LSTM后的那個矩陣,就被當做是emit score了
# the ith entry of trans_score is the score of transitioning to
# next_tag from i
trans_score = self.transitions[next_tag].view(1, -1) #維度是1*5
# The ith entry of next_tag_var is the value for the
# edge (i -> next_tag) before we do log-sum-exp
#第一次迭代時理解:
# trans_score所有其他標簽到B標簽的概率
# 由lstm運行進入隱層再到輸出層得到標簽B的概率,emit_score維度是1*5,5個值是相同的
next_tag_var = forward_var + trans_score + emit_score
# The forward variable for this tag is log-sum-exp of all the
# scores.
alphas_t.append(log_sum_exp(next_tag_var).unsqueeze(0))
#此時的alphas t 是一個長度為5,例如<class 'list'>: [tensor(0.8259), tensor(2.1739), tensor(1.3526), tensor(-9999.7168), tensor(-0.7102)]
forward_var = torch.cat(alphas_t).view(1, -1)#到第(t-1)step時5個標簽的各自分數
terminal_var = forward_var + self.transitions[self.tag_to_ix[STOP_TAG]] #最后只將最后一個單詞的forward var與轉移 stop tag的概率相加 tensor([[ 21.1036, 18.8673, 20.7906, -9982.2734, -9980.3135]])
alpha = log_sum_exp(terminal_var) #alpha是一個0維的tensor
return alpha
#得到feats
def _get_lstm_features(self, sentence):
self.hidden = self.init_hidden()
#embeds = self.word_embeds(sentence).view(len(sentence), 1, -1)
embeds = self.word_embeds(sentence)
embeds = embeds.unsqueeze(1)
lstm_out, self.hidden = self.lstm(embeds, self.hidden)#11*1*4
lstm_out = lstm_out.view(len(sentence), self.hidden_dim) #11*4
lstm_feats = self.hidden2tag(lstm_out)#11*5 is a linear layer
return lstm_feats
#得到gold_seq tag的score 即根據真實的label 來計算一個score,但是因為轉移矩陣是隨機生成的,故算出來的score不是最理想的值
def _score_sentence(self, feats, tags):
# Gives the score of a provided tag sequence #feats 11*5 tag 11 維
score = autograd.Variable(torch.Tensor([0]))
tags = torch.cat([torch.LongTensor([self.tag_to_ix[START_TAG]]), tags]) #將START_TAG的標簽3拼接到tag序列最前面,這樣tag就是12個了
for i, feat in enumerate(feats):
#self.transitions[tags[i + 1], tags[i]] 實際得到的是從標簽i到標簽i+1的轉移概率
#feat[tags[i+1]], feat是step i 的輸出結果,有5個值,對應B, I, E, START_TAG, END_TAG, 取對應標簽的值
#transition【j,i】 就是從i ->j 的轉移概率值
score = score + self.transitions[tags[i + 1], tags[i]] + feat[tags[i + 1]]
score = score + self.transitions[self.tag_to_ix[STOP_TAG], tags[-1]]
return score
#解碼,得到預測的序列,以及預測序列的得分
def _viterbi_decode(self, feats):
backpointers = []
# Initialize the viterbi variables in log space
init_vvars = torch.Tensor(1, self.tagset_size).fill_(-10000.)
init_vvars[0][self.tag_to_ix[START_TAG]] = 0
# forward_var at step i holds the viterbi variables for step i-1
forward_var = autograd.Variable(init_vvars)
for feat in feats:
bptrs_t = [] # holds the backpointers for this step
viterbivars_t = [] # holds the viterbi variables for this step
for next_tag in range(self.tagset_size):
# next_tag_var[i] holds the viterbi variable for tag i at the
# previous step, plus the score of transitioning
# from tag i to next_tag.
# We don't include the emission scores here because the max
# does not depend on them (we add them in below)
next_tag_var = forward_var + self.transitions[next_tag] #其他標簽(B,I,E,Start,End)到標簽next_tag的概率
best_tag_id = argmax(next_tag_var)
bptrs_t.append(best_tag_id)
viterbivars_t.append(next_tag_var[0][best_tag_id].view(1))
# Now add in the emission scores, and assign forward_var to the set
# of viterbi variables we just computed
forward_var = (torch.cat(viterbivars_t) + feat).view(1, -1)#從step0到step(i-1)時5個序列中每個序列的最大score
backpointers.append(bptrs_t) #bptrs_t有5個元素
# Transition to STOP_TAG
terminal_var = forward_var + self.transitions[self.tag_to_ix[STOP_TAG]]#其他標簽到STOP_TAG的轉移概率
best_tag_id = argmax(terminal_var)
path_score = terminal_var[0][best_tag_id]
# Follow the back pointers to decode the best path.
best_path = [best_tag_id]
for bptrs_t in reversed(backpointers):#從后向前走,找到一個best路徑
best_tag_id = bptrs_t[best_tag_id]
best_path.append(best_tag_id)
# Pop off the start tag (we dont want to return that to the caller)
start = best_path.pop()
assert start == self.tag_to_ix[START_TAG] # Sanity check
best_path.reverse()# 把從后向前的路徑正過來
return path_score, best_path
def neg_log_likelihood(self, sentence, tags):
feats = self._get_lstm_features(sentence)#11*5 經過了LSTM+Linear矩陣后的輸出,之后作為CRF的輸入。
forward_score = self._forward_alg(feats) #0維的一個得分,20.*來着
gold_score = self._score_sentence(feats, tags)#tensor([ 4.5836])
return forward_score - gold_score
def forward(self, sentence): # dont confuse this with _forward_alg above.
# Get the emission scores from the BiLSTM
lstm_feats = self._get_lstm_features(sentence)
# Find the best path, given the features.
score, tag_seq = self._viterbi_decode(lstm_feats)
return score, tag_seq
START_TAG = "<START>"
STOP_TAG = "<STOP>"
EMBEDDING_DIM = 5
HIDDEN_DIM = 4
# Make up some training data
training_data = [("the wall street journal reported today that apple corporation made money".split(), "B I I I O O O B I O O".split()),
("georgia tech is a university in georgia".split(), "B I O O O O B".split())]
word_to_ix = {}
for sentence, tags in training_data:
for word in sentence:
if word not in word_to_ix:
word_to_ix[word] = len(word_to_ix)
tag_to_ix = {"B": 0, "I": 1, "O": 2, START_TAG: 3, STOP_TAG: 4}
model = BiLSTM_CRF(len(word_to_ix), tag_to_ix, EMBEDDING_DIM, HIDDEN_DIM)
optimizer = optim.SGD(model.parameters(), lr=0.01, weight_decay=1e-4)
# Check predictions before training
# precheck_sent = prepare_sequence(training_data[0][0], word_to_ix)
# precheck_tags = torch.LongTensor([tag_to_ix[t] for t in training_data[0][1]])
# print(model(precheck_sent))
# Make sure prepare_sequence from earlier in the LSTM section is loaded
for epoch in range(1): # again, normally you would NOT do 300 epochs, it is toy data
for sentence, tags in training_data:
# Step 1. Remember that Pytorch accumulates gradients.
# We need to clear them out before each instance
model.zero_grad()
# Step 2. Get our inputs ready for the network, that is,
# turn them into Variables of word indices.
sentence_in = prepare_sequence(sentence, word_to_ix)
targets = torch.LongTensor([tag_to_ix[t] for t in tags])
# Step 3. Run our forward pass.
neg_log_likelihood = model.neg_log_likelihood(sentence_in, targets)#tensor([ 15.4958]) 最大的可能的值與 根據隨機轉移矩陣 計算的真實值 的差
# Step 4. Compute the loss, gradients, and update the parameters by
# calling optimizer.step()
neg_log_likelihood.backward()#卧槽,這就能更新啦???進行了反向傳播,算了梯度值。debug中可以看到,transition的_grad 有了值 torch.Size([5, 5])
optimizer.step()
# Check predictions after training
precheck_sent = prepare_sequence(training_data[0][0], word_to_ix)
print(model(precheck_sent)[0]) #得分
print('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^')
print(model(precheck_sent)[1]) #tag sequence
心得的地方:
反向傳播不需要一定使用forward(),而且不需要定義loss=nn.MSError()等,直接score1 - score2 ,就可以反向傳播了。
無論兩個矩陣你咋操作,只要滿足,不管你是只取一行,還是幾行,加減乘數。只要能夠滿足這個式子,就能夠反向傳播,前提是 self.transitions = nn.Parameter(torch.randn(self.tagset_size, self.tagset_size)) 將你想要更新的矩陣,放入到module的參數中,這樣才能夠更新。
即便你是這樣用的:
for feat in feats: #feat的維度是5 依次把每一行取出來~
alphas_t = [] # The forward variables at this timestep
for next_tag in range(self.tagset_size):#next tag 就是簡單 i,從0到len
# broadcast the emission score: it is the same regardless of
# the previous tag
emit_score = feat[next_tag].view(1, -1).expand(1, self.tagset_size) #維度是1*5 噢噢!原來,LSTM后的那個矩陣,就被當做是emit score了
# the ith entry of trans_score is the score of transitioning to
# next_tag from i
trans_score = self.transitions[next_tag].view(1, -1) #維度是1*5
# The ith entry of next_tag_var is the value for the
# edge (i -> next_tag) before we do log-sum-exp
#第一次迭代時理解:
# trans_score所有其他標簽到B標簽的概率
# 由lstm運行進入隱層再到輸出層得到標簽B的概率,emit_score維度是1*5,5個值是相同的
next_tag_var = forward_var + trans_score + emit_score
# The forward variable for this tag is log-sum-exp of all the
# scores.
alphas_t.append(log_sum_exp(next_tag_var).unsqueeze(0))
#此時的alphas t 是一個長度為5,例如<class 'list'>: [tensor(0.8259), tensor(2.1739), tensor(1.3526), tensor(-9999.7168), tensor(-0.7102)]
forward_var = torch.cat(alphas_t).view(1, -1)#到第(t-1)step時5個標簽的各自分數
terminal_var = forward_var + self.transitions[self.tag_to_ix[STOP_TAG]] #最后只將最后一個單詞的forward var與轉移 stop tag的概率相加 tensor([[ 21.1036, 18.8673, 20.7906, -9982.2734, -9980.3135]])
alpha = log_sum_exp(terminal_var) #alpha是一個0維的tensor
或者是這樣用的
score = autograd.Variable(torch.Tensor([0]))
tags = torch.cat([torch.LongTensor([self.tag_to_ix[START_TAG]]), tags]) #將START_TAG的標簽3拼接到tag序列最前面,這樣tag就是12個了
for i, feat in enumerate(feats):
#self.transitions[tags[i + 1], tags[i]] 實際得到的是從標簽i到標簽i+1的轉移概率
#feat[tags[i+1]], feat是step i 的輸出結果,有5個值,對應B, I, E, START_TAG, END_TAG, 取對應標簽的值
#transition【j,i】 就是從i ->j 的轉移概率值
score = score + self.transitions[tags[i + 1], tags[i]] + feat[tags[i + 1]]
score = score + self.transitions[self.tag_to_ix[STOP_TAG], tags[-1]]
return score
看樣子,每個循環里只是去了轉移矩陣的一行,或者就是一個值,進行操作,但是!轉移矩陣就是能夠更新!!!至於為什么能夠更新!!我不知道:(
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
2018.12.12
心得,發射矩陣是 lstm算出來的,是要通過網絡學習的。轉移矩陣是單獨定義的,要學習的。初始矩陣,是[-1000,-1000,-1000,0,-1000]固定的,因為當加了開始符號后,則第一個位置是開始符號的概率是100%。
顯式的加入了start標記,隱式的使用了end標記(總是最后多一步轉移到end)的分數
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
以上都是個人理解,懇請勘誤!
Pytorch Bi-LSTM + CRF 代碼詳解
閱讀數 9317
久聞LSTM+CRF的效果強大,最近在看Pytorch官網文檔的時候,看到了這段代碼,前前后后查了很多資料,終於把代碼弄懂了。我希望在后來人看這段代碼的時候,直接就看我的博客就能完全弄懂這段代碼。看這...
博文
來自: Call Me Hi Johnny~~
ancient_wizard_wjs: 你好,請問一下你知道如何將完整的代碼在GPU上跑通嗎,我的老是報錯
Traceback (most recent call last):
File "lstm_crf.py", line 281, in <module>
loss = model.neg_log_likelihood(sentence_in, targets)
File "lstm_crf.py", line 205, in neg_log_likelihood
feats = self._get_lstm_features(sentence)
File "lstm_crf.py", line 120, in _get_lstm_features
lstm_out, self.hidden = self.lstm(embeds, self.hidden) # 11*1*4
File "/home/sjwang/py/python3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 489, in __call__
result = self.forward(*input, **kwargs)
File "/home/sjwang/py/python3/lib/python3.6/site-packages/torch/nn/modules/rnn.py", line 179, in forward
self.dropout, self.training, self.bidirectional, self.batch_first)
RuntimeError: Input and hidden tensors are not at the same device, found input tensor at cuda:0 and hidden tensor at cpu
(3個月前#3樓)查看回復(1)
for_android_d: return max_score + torch.log(torch.sum(torch.exp(vec - max_score_broadcast)))#為什么指數之后再求和,而后才log呢。博主看明白這一行代碼了嗎,特別是vec-max_score_broadcast不知道是怎么回事,可以提供一個推導過程嗎
---------------------
作者:Jason__Liang
來源:CSDN
原文:https://blog.csdn.net/Jason__Liang/article/details/81772632
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!