欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

CRF代码及实现原理(二)

程序员文章站 2022-07-14 16:17:13
...

主要介绍CRF代码实现
 代码来源:pytorch官网
代码链接: https://pytorch.org/tutorials/beginner/nlp/advanced_tutorial.html
配合另一篇文章讲解,看此篇之前,最好看一下另一篇文章(CRF原理以及维特比解码),看完之后会很容易理解
另一篇文章链接:https://blog.csdn.net/cpluss/article/details/88824303
注意看汉语注释,完整的代码详见上面的链接

#代码的主体部分
START_TAG = "<START>"
STOP_TAG = "<STOP>"
EMBEDDING_DIM = 5
HIDDEN_DIM = 4

# 简单的训练数据
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 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.
        #这里是重点,model.neg_log_likelihood是主要的函数
        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()

# 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!

neg_log_likelihood函数

    def neg_log_likelihood(self, sentence, tags):
        #feats是通过一个bi-lstm得到的特征,维度为(seq_length, tagset_size),此处与crf关系不太大,因此不考虑
        #tagset_size 表示为tag的数量,例如此代码中为5
        feats = self._get_lstm_features(sentence)
        #计算得分
        forward_score = self._forward_alg(feats)
        #计算实际得分
        gold_score = self._score_sentence(feats, tags)
        #计算误差,之后有loss.backward进行训练
        return forward_score - gold_score

_forward_alg函数

    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就是另一篇文章中提到的不断更新的δ参数
        forward_var = init_alphas

        # Iterate through the sentence
        #这里的每一个feat,对应一个单词
        for feat in feats:
            alphas_t = []  # The forward tensors at this timestep
            #这里每一个next_tag对应一个词性,下面计算的是:
            #单词feat词性为next_tag时的得分
            for next_tag in range(self.tagset_size):
                # broadcast the emission score: it is the same regardless of
                # the previous tag
                #这个得分就是另一篇文章中提到的输入x对于y的影响的得分
                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
                #这个transition矩阵就是另一篇文章中提到t矩阵
                #transition[i][j]代表j词性转变为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