使用Pytorch框架中定义好的biLSTM_CRF模型和超参数,主要目的是加深学习印象;
过去一段时间对序列标注任务学习的梳理,学习的过程中有不断修正之前的理解里谬误的地方;本文是对tutorial的示范例子的一次依葫芦画瓢,仅作为对之前学习内容的回顾总结和实践,最重要的还是先对知识和模型的学习!
pytorch的官方文档
学习过程做的笔记:
对biLSTM_CRF模型的理解
对pytorch官方文档里biLSTM_CRF模型的源码学习(一)整体理解
(二)预定义方法、模型的初始化工作
(三)前向传播过程
上述是用序列标注任务(词性标注和命名实体识别)来学习bilstm_crf模型的,前提是理解序列标注任务
对词性标注任务、条件随机场crf、hmm模型及两者区别的理解
如果对hmm模型、以及序列标注任务中转移概率分布、发射概率分布概念的理解有困难,可以先从一个小例子开始学习hmm模型
用C++语言实现hmm+viterbi算法做词性标注任务(给定hmm模型,侧重于理解hmm和viterbi的算法部分)
理解给定hmm模型下完成词性标注任务的过程后,可以尝试⬇️基于统计、使用参数估计方法定义自己的hmm模型,并使用模型做词性标注任务
用python语言实现hmm+viterbi算法做词性标注任务(与本文使用相同的数据集)
1.开始标签、结束标签、超参数(词向量维度、隐藏层向量的维度)
START_TAG = ""
STOP_TAG = ""
EMBEDDING_DIM = 5
HIDDEN_DIM = 4
2.使用已经标注好的人民日报语料库作为数据集,读入文件
词序列和标签序列保存在list_vocab和list_pos
f = open("199801_dependency_treebank_2003pos2103230114.txt","r")
txt = f.read() # 一次性读入全部
f.close()
lines = txt.split("\n") # 按行切割
row = 0 # 源文本文件从第一行开始每隔四行为词汇统计行 中文分词结果
list_vocab=[]
while row<len(lines):
for word in lines[row].split(): #将分好的词全部加进list_vocab中
list_vocab.append(word)
row+=5
row = 1 # 源文本文件从第二行开始每隔四行为词性标注统计行
list_pos=[]
while row<len(lines):
for pos in lines[row].split(): #将分好的词全部加进list_vocab中
list_pos.append(pos)
row+=5
3.建立训练集数据,建立词在词表中的索引,标签在标签集中的索引,索引值到类标签的映射
training_data = [(list_vocab,list_pos)] #训练数据是(词序列,词性序列)的元组
word_to_ix = {}
for word in set(list_vocab):
word_to_ix[word] = len(word_to_ix) # 词表
tag_to_ix={}
ix_to_tag={} # 建立标签下标->标签的映射 便于输出预测结果时直接输出标签值
for tag in set(list_pos):
tag_to_ix[tag] = len(tag_to_ix) #标签表
ix_to_tag[tag_to_ix[tag]] = tag
tag_to_ix[START_TAG] = len(tag_to_ix)
ix_to_tag[tag_to_ix[START_TAG]] = START_TAG
tag_to_ix[STOP_TAG] = len(tag_to_ix)
ix_to_tag[tag_to_ix[STOP_TAG]] = STOP_TAG
这里构建索引表的tag_to_ix[tag] = len(tag_to_ix)是在pytorch的tutorial参考文档学到的,不用自己再创建一个index=0,index+=1,代码美观。因为列表中会有重复出现,用去重后的集合降低时间复杂度。
4.定义模型
添加一个自定义方法,由标签的索引序列得到标签序列
# Author: Robert Guthrie
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.optim as optim
from make_data import *
torch.manual_seed(1)
def argmax(vec):
# return the argmax as a python int
_, idx = torch.max(vec, 1)
return idx.item()
def prepare_sequence(seq, to_ix):
idxs = [to_ix[w] for w in seq]
return torch.tensor(idxs, dtype=torch.long)
def ix_sequence_to_tag_sequence(idxs,ix_to_tag):
tags = [ix_to_tag[id] for id in idxs]
return tags
# Compute log sum exp in a numerically stable way for the forward algorithm
def log_sum_exp(vec):
max_score = vec[0, argmax(vec)]
max_score_broadcast = max_score.view(1, -1).expand(1, vec.size()[1])
return max_score + \
torch.log(torch.sum(torch.exp(vec - max_score_broadcast)))
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 (torch.randn(2, 1, self.hidden_dim // 2),
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.full((1, self.tagset_size), -10000.)
# START_TAG has all of the score.
init_alphas[0][self.tag_to_ix[START_TAG]] = 0.
# Wrap in a variable so that we will get automatic backprop
forward_var = init_alphas
# Iterate through the sentence
for feat in feats:
alphas_t = [] # The forward tensors at this timestep
for next_tag in range(self.tagset_size):
# 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)
# 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)
# The ith entry of next_tag_var is the value for the
# edge (i -> next_tag) before we do log-sum-exp
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).view(1))
forward_var = torch.cat(alphas_t).view(1, -1)
terminal_var = forward_var + self.transitions[self.tag_to_ix[STOP_TAG]]
alpha = log_sum_exp(terminal_var)
return alpha
def _get_lstm_features(self, sentence):
self.hidden = self.init_hidden()
embeds = self.word_embeds(sentence).view(len(sentence), 1, -1)
lstm_out, self.hidden = self.lstm(embeds, self.hidden)
lstm_out = lstm_out.view(len(sentence), self.hidden_dim)
lstm_feats = self.hidden2tag(lstm_out)
return lstm_feats
def _score_sentence(self, feats, tags):
# Gives the score of a provided tag sequence
score = torch.zeros(1)
tags = torch.cat([torch.tensor([self.tag_to_ix[START_TAG]], dtype=torch.long), tags])
for i, feat in enumerate(feats):
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.full((1, self.tagset_size), -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 = 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]
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)
backpointers.append(bptrs_t)
# Transition to STOP_TAG
terminal_var = forward_var + self.transitions[self.tag_to_ix[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_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)
forward_score = self._forward_alg(feats)
gold_score = self._score_sentence(feats, tags)
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
5.5.创建一个BiLSTM_CRF模型,只训练一次,之后通过加载保存好的模型参数,使用预训练好的模型;定义优化器、超参数(学习率、权重衰减)
model=BiLSTM_CRF(len(word_to_ix), tag_to_ix, EMBEDDING_DIM, HIDDEN_DIM) # 创建一个一模一样的模型
# model.load_state_dict(torch.load("POStagging.pth")) # 加载预训练模型的参数
optimizer = optim.SGD(model.parameters(), lr=0.01, weight_decay=1e-4)
6.用训练前的模型预测
# Check predictions before training
with torch.no_grad():
print("训练前模型对输入序列的预测标签序列")
precheck_sent = prepare_sequence(training_data[0][0], word_to_ix)
print(training_data[0][0])
idxs = model(precheck_sent)[1] # tuple (tensor ,list)
print(ix_sequence_to_tag_sequence(idxs, ix_to_tag))
model(sentence)返回的是一个元组(张量、输出向量)
因为biLSTM是RNN的变种,所以每次输出两个向量(隐藏状态向量和输出向量)
所以这里元组的第一个元素(张量)是RNN网络处理完最后一个时间步的隐状态,第二个元素(idxs序列)是模型为输入序列标注的词性序列(索引值)
调用自定义方法ix_sequence_to_tag_sequence(idxs,ix_to_tag)将其转化为词性序列
# 如果是机器使用测试集评估预测的accuracy,不需要这一步,
y_test = tag_to_ix(y_test)
再对y_pred和y_test进行比较即可
这里我们为了肉眼查看测试数据的输入序列和输出序列来评估模型效果
7.训练过程,并保存好训练的模型
# Make sure prepare_sequence from earlier in the LSTM section is loaded
for epoch in range(
300): # 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 Tensors of word indices.
sentence_in = prepare_sequence(sentence, word_to_ix)
targets = torch.tensor([tag_to_ix[t] for t in tags], dtype=torch.long)
# Step 3. Run our forward pass.
loss = model.neg_log_likelihood(sentence_in, targets)
# Step 4. Compute the loss, gradients, and update the parameters by
# calling optimizer.step()
loss.backward()
optimizer.step()
torch.save(model.state_dict(),"POStagging.pth") # 保存训练好的模型
8.使用训练后的模型进行预测,查看模型效果
# Check predictions after training
with torch.no_grad():
print("训练后模型对输入序列的预测标签序列")
precheck_sent = prepare_sequence(training_data[0][0], word_to_ix)
print(training_data[0][0])
idxs = model(precheck_sent)[1] #tuple (tensor ,list)
print(ix_sequence_to_tag_sequence(idxs, ix_to_tag))
# We got it!