### Bi-LSTM Conditional Random Field
### pytorch tutorials https://pytorch.org/tutorials/beginner/nlp/advanced_tutorial.html
### 模型主要结构:
![title](sources/bilstm.png)
pytorch bilstm crf的教程,注意 这里不支持批处理
Python version: 3.7.4 (default, Aug 13 2019, 20:35:49) [GCC 7.3.0]
Torch version: 1.4.0
# Author: Robert Guthrieimport torch
import torch.autograd as autograd
import torch.nn as nn
import torch.optim as optimtorch.manual_seed(1)
def argmax(vec):# return the argmax as a python int# 返回vec的dim为1维度上的最大值索引_, idx = torch.max(vec, 1)return idx.item()def prepare_sequence(seq, to_ix):# 将句子转化为IDidxs = [to_ix[w] for w in seq]return torch.tensor(idxs, dtype=torch.long)# Compute log sum exp in a numerically stable way for the forward algorithm
# 前向算法是不断累积之前的结果,这样就会有个缺点
# 指数和累积到一定程度后,会超过计算机浮点值的最大值,变成inf,这样取log后也是inf
# 为了避免这种情况,用一个合适的值clip去提指数和的公因子,这样就不会使某项变得过大而无法计算
# SUM = log(exp(s1)+exp(s2)+...+exp(s100))
# = log{exp(clip)*[exp(s1-clip)+exp(s2-clip)+...+exp(s100-clip)]}
# = clip + log[exp(s1-clip)+exp(s2-clip)+...+exp(s100-clip)]
# where clip=max
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 # word embedding dimself.hidden_dim = hidden_dim # Bi-LSTM hidden dimself.vocab_size = vocab_size self.tag_to_ix = tag_to_ixself.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.# 将BiLSTM提取的特征向量映射到特征空间,即经过全连接得到发射分数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.# 转移矩阵的参数初始化,transitions[i,j]代表的是从第j个tag转移到第i个tag的转移分数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# 初始化所有其他tag转移到START_TAG的分数非常小,即不可能由其他tag转移到START_TAG# 初始化STOP_TAG转移到所有其他tag的分数非常小,即不可能由STOP_TAG转移到其他tagself.transitions.data[tag_to_ix[START_TAG], :] = -10000self.transitions.data[:, tag_to_ix[STOP_TAG]] = -10000self.hidden = self.init_hidden()def init_hidden(self):# 初始化LSTM的参数return (torch.randn(2, 1, self.hidden_dim // 2),torch.randn(2, 1, self.hidden_dim // 2))def _get_lstm_features(self, sentence):# 通过Bi-LSTM提取特征self.hidden = self.init_hidden()# 因此,embeds 的最终数据形式是一个三维张量,形状为 (seq_len, 1, embed_dim),其中:# seq_len 是句子的长度(即单词的数量)。# 1 表示批次大小,表明当前处理的是单个句子。# embed_dim 是每个单词的嵌入向量维度。# 这种形状非常适合直接传递给 PyTorch 的 LSTM 层进行处理,因为 LSTM 层期望输入有三个维度,分别对应序列长度# 、批次大小和特征数(或输入大小)。如果你希望模型能够处理多个句子(即更大的批次),你应该相应地调整代码,# 使得 sentence 可以同时包含多条序列,并且批次大小不固定为1。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_featsdef _score_sentence(self, feats, tags):# Gives the score of a provided tag sequence# 计算给定tag序列的分数,即一条路径的分数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 scoredef _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.# 初始化step 0即START位置的发射分数,START_TAG取0其他位置取-10000init_alphas[0][self.tag_to_ix[START_TAG]] = 0.# Wrap in a variable so that we will get automatic backprop# 将初始化START位置为0的发射分数赋值给previousprevious = init_alphas# Iterate through the sentence# 迭代整个句子for obs in feats:# The forward tensors at this timestep# 当前时间步的前向tensoralphas_t = []for next_tag in range(self.tagset_size):# broadcast the emission score: it is the same regardless of the previous tag# 取出当前tag的发射分数,与之前时间步的tag无关emit_score = obs[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# 取出当前tag由之前tag转移过来的转移分数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 = previous + trans_score + emit_score# The forward variable for this tag is log-sum-exp of all the scores.# 对当前分数取log-sum-expalphas_t.append(log_sum_exp(next_tag_var).view(1))# 更新previous 递推计算下一个时间步previous = torch.cat(alphas_t).view(1, -1)# 考虑最终转移到STOP_TAGterminal_var = previous + self.transitions[self.tag_to_ix[STOP_TAG]]# 计算最终的分数scores = log_sum_exp(terminal_var)return scoresdef _viterbi_decode(self, feats):backpointers = []# Initialize the viterbi variables in log space# 初始化viterbi的previous变量init_vvars = torch.full((1, self.tagset_size), -10000.)init_vvars[0][self.tag_to_ix[START_TAG]] = 0previous = init_vvarsfor obs in feats:# holds the backpointers for this step# 保存当前时间步的回溯指针bptrs_t = []# holds the viterbi variables for this step# 保存当前时间步的viterbi变量viterbivars_t = [] 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)# 维特比算法记录最优路径时只考虑上一步的分数以及上一步tag转移到当前tag的转移分数# 并不取决与当前tag的发射分数next_tag_var = previous + 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# 更新previous,加上当前tag的发射分数obsprevious = (torch.cat(viterbivars_t) + obs).view(1, -1)# 回溯指针记录当前时间步各个tag来源前一步的tagbackpointers.append(bptrs_t)# Transition to STOP_TAG# 考虑转移到STOP_TAG的转移分数terminal_var = previous + 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]# best_tag_id作为线头,反向遍历backpointers找到最优路径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_TAGstart = best_path.pop()assert start == self.tag_to_ix[START_TAG] # Sanity checkbest_path.reverse()return path_score, best_pathdef neg_log_likelihood(self, sentence, tags):# CRF损失函数由两部分组成,真实路径的分数和所有路径的总分数。# 真实路径的分数应该是所有路径中分数最高的。# log真实路径的分数/log所有可能路径的分数,越大越好,构造crf loss函数取反,loss越小越好feats = self._get_lstm_features(sentence)forward_score = self._forward_alg(feats)gold_score = self._score_sentence(feats, tags)return forward_score - gold_scoredef forward(self, sentence): # dont confuse this with _forward_alg above.# Get the emission scores from the BiLSTM# 通过BiLSTM提取发射分数lstm_feats = self._get_lstm_features(sentence)# Find the best path, given the features.# 根据发射分数以及转移分数,通过viterbi解码找到一条最优路径score, tag_seq = self._viterbi_decode(lstm_feats)return score, tag_seqSTART_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
# 训练前检查模型预测结果
with torch.no_grad():precheck_sent = prepare_sequence(training_data[0][0], word_to_ix)precheck_tags = torch.tensor([tag_to_ix[t] for t in training_data[0][1]], dtype=torch.long)print(model(precheck_sent))# 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 datafor sentence, tags in training_data:# Step 1. Remember that Pytorch accumulates gradients.# We need to clear them out before each instance# 第一步,pytorch梯度累积,需要清零梯度model.zero_grad()# Step 2. Get our inputs ready for the network, that is,# turn them into Tensors of word indices.# 第二步,将输入转化为tensorssentence_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.# 进行前向计算,取出crf lossloss = model.neg_log_likelihood(sentence_in, targets)# Step 4. Compute the loss, gradients, and update the parameters by# calling optimizer.step()# 第四步,计算loss,梯度,通过optimier更新参数loss.backward()optimizer.step()# Check predictions after training
# 训练结束查看模型预测结果,对比观察模型是否学到
with torch.no_grad():precheck_sent = prepare_sequence(training_data[0][0], word_to_ix)print(model(precheck_sent))
# We got it!
改成批处理关键代码 previous_score = score[t - 1].view(batch_size, -1, 1)
def viterbi_decode(self, h: FloatTensor, mask: BoolTensor) -> List[List[int]]:"""decode labels using viterbi algorithm:param h: hidden matrix (batch_size, seq_len, num_labels):param mask: mask tensor of each sequencein mini batch (batch_size, batch_size):return: labels of each sequence in mini batch"""batch_size, seq_len, _ = h.size()# prepare the sequence lengths in each sequenceseq_lens = mask.sum(dim=1)# In mini batch, prepare the score# from the start sequence to the first labelscore = [self.start_trans.data + h[:, 0]]path = []for t in range(1, seq_len):# extract the score of previous sequence# (batch_size, num_labels, 1)previous_score = score[t - 1].view(batch_size, -1, 1)# extract the score of hidden matrix of sequence# (batch_size, 1, num_labels)h_t = h[:, t].view(batch_size, 1, -1)# extract the score in transition# from label of t-1 sequence to label of sequence of t# self.trans_matrix has the score of the transition# from sequence A to sequence B# (batch_size, num_labels, num_labels)score_t = previous_score + self.trans_matrix + h_t# keep the maximum value# and point where maximum value of each sequence# (batch_size, num_labels)best_score, best_path = score_t.max(1)score.append(best_score)path.append(best_path)
torchcrf 使用 支持批处理,torchcrf的简单使用-CSDN博客文章浏览阅读9.7k次,点赞5次,收藏33次。本文介绍了如何在PyTorch中安装和使用TorchCRF库,重点讲解了CRF模型参数设置、自定义掩码及损失函数的计算。作者探讨了如何将CRF的NLL损失与交叉熵结合,并通过自适应权重优化训练过程。虽然在单任务中效果不显著,但对于多任务学习提供了有价值的方法。https://blog.csdn.net/csdndogo/article/details/125541213
torchcrf的简单使用-CSDN博客
为了防止文章丢失 ,吧内容转发在这里
https://blog.csdn.net/csdndogo/article/details/125541213
. 安装torchcrf,模型使用
安装:pip install TorchCRF
CRF的使用:在官网里有简单的使用说明
注意输入的格式。在其他地方下载的torchcrf有多个版本,有些版本有batch_first参数,有些没有,要看清楚有没有这个参数,默认batch_size是第一维度。
这个代码是我用来熟悉使用crf模型和损失函数用的,模拟多分类任务输入为随机数据和随机标签,所以最后的结果预测不能很好的跟标签对应。
import torch
import torch.nn as nn
import numpy as np
import random
from TorchCRF import CRF
from torch.optim import Adam
seed = 100
def seed_everything(seed=seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
num_tags = 5
model = CRF(num_tags, batch_first=True) # 这里根据情况而定
seq_len = 3
batch_size = 50
seed_everything()
trainset = torch.randn(batch_size, seq_len, num_tags) # features
traintags = (torch.rand([batch_size, seq_len])*4).floor().long() # (batch_size, seq_len)
testset = torch.randn(5, seq_len, num_tags) # features
testtags = (torch.rand([5, seq_len])*4).floor().long() # (batch_size, seq_len)
# 训练阶段
for e in range(50):
optimizer = Adam(model.parameters(), lr=0.05)
model.train()
optimizer.zero_grad()
loss = -model(trainset, traintags)
print('epoch{}: loss score is {}'.format(e, loss))
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(),5)
optimizer.step()
#测试阶段
model.eval()
loss = model(testset, testtags)
model.decode(testset)
1.1模型参数,自定义掩码mask注意事项
def forward(self, emissions, labels: LongTensor, mask: BoolTensor)
1
分别为发射矩阵(各标签的预测值),标签,掩码(注意这里的mask类型为BoolTensor)
注意:此处自定义mask掩码时,使用LongTensor类型的[1,1,1,1,0,0]会报错,需要转换成ByteTensor,下面是一个简单的获取mask的函数,输入为标签数据:
def get_crfmask(self, labels):
crfmask = []
for batch in labels:
res = [0 if d == -1 else 1 for d in batch]
crfmask.append(res)
return torch.ByteTensor(crfmask)
运行运行
2. CRF的损失函数是什么?
损失函数由真实转移路径值和所有可能情况路径转移值两部分组成,损失函数的公式为
分子为真实转移路径值,分母为所有路径总分数,上图公式在crf原始代码中为:
def forward(
self, h: FloatTensor, labels: LongTensor, mask: BoolTensor) -> FloatTensor:
log_numerator = self._compute_numerator_log_likelihood(h, labels, mask)
log_denominator = self._compute_denominator_log_likelihood(h, mask)
return log_numerator - log_denominator
CRF损失函数值为负对数似然函数(NLL),所以如果原来的模型损失函数使用的是交叉熵损失函数,两个损失函数相加时要对CRF返回的损失取负。
loss = -model(trainset, traintags)
1
3. 如何联合CRF的损失函数和自己的网络模型的交叉熵损失函数进行训练?
我想在自己的模型上添加CRF,就需要联合原本的交叉熵损失函数和CRF的损失函数,因为CRF输出的时NLL,所以在模型在我仅对该损失函数取负之后和原先函数相加。
loss2 = -crf_layer(log_prob, label, mask=crfmask)
loss1 = loss_function(log_prob.permute(0, 2, 1), label)
loss = loss1 + loss2
loss.backward()
缺陷: 效果不佳,可以尝试对loss2添加权重。此处贴一段包含两个损失函数的自适应权重训练的函数。
3.1.自适应损失函数权重
由于CRF返回的损失与原来的损失数值不在一个量级,所以产生了自适应权重调整两个权重的大小来达到优化的目的。自适应权重原本属于多任务学习部分,未深入了解,代码源自某篇复现论文的博客。
class AutomaticWeightedLoss(nn.Module):
def __init__(self, num=2):
super(AutomaticWeightedLoss, self).__init__()
params = torch.ones(num, requires_grad=True)
self.params = torch.nn.Parameter(params)
def forward(self, *x):
loss_sum = 0
for i, loss in enumerate(x):
loss_sum += 0.5 / (self.params[i] ** 2) * loss + torch.log(1 + self.params[i] ** 2)
return loss_sum