BILSTM-CRF代码
代码来源于命名实体识别(NER):BiLSTM-CRF原理介绍+Pytorch_Tutorial代码解析
第一部分:导包
1.torch.nn包中主要包含了用来搭建各个层的模块(Modules),比如全连接、二维卷积、池化等;torch.nn包中还包含了一系列有用的loss函数。
2.torch.optim包则主要包含了用来更新参数的优化算法,比如SGD、AdaGrad、RMSProp、 Adam等。
3.import torch.autograd as autograd这是求自动微分的
第二部分
用于设置随机初始化的种子,即上述的编号,编号固定,每次获取的随机数固定。
1.设置标签与BILSTM隐藏层
首先确定标签个数:SBIOE
BILSTM的隐藏特征个数4,单向为2。
START_TAG = "<START>"
STOP_TAG = "<STOP>"
EMBEDDING_DIM = 5 # 由于标签一共有B\I\O\START\STOP 5个,所以embedding_dim为5
HIDDEN_DIM = 4 # 这其实是BiLSTM的隐藏层的特征数量,因为是双向所以是2倍,单向为2
2.数据集
这里用两个句子来测试,每一个句子对应的词性都有正确的标签。
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()
)]
3.处理数据集中句子的词,不重复的将句子中的词拿出来并标号。
设置一个word_to_ix存储句子中每一个单词。
首先我们拿出每一个句子跟其对应的标签,用sentence与tag循环每一个句子,比如第0次抽出来的就是第一个句子"the wall …money",与他的标签"B I I …0"。
现在我们只存储出现过的单词(不管标签),下面代码解释:
word_to_ix = {
}
for sentence, tags in training_data:
for word in sentence:
if word not in word_to_ix: #word_to_ix是否包含左边的内容
word_to_ix[word] = len(word_to_ix)
if word not in word_to_ix:
word_to_ix[word] = len(word_to_ix)
这句就是说word_to ix没有word这句单词时候,就存储进去,并且给每一个新的word赋值,赋的值就是长度。
最终的结果为都在word_to_ix中:
word_to_ix: {‘the’: 0, ‘wall’: 1, ‘street’: 2, ‘journal’: 3, ‘reported’: 4, ‘today’: 5, ‘that’: 6, ‘apple’: 7, ‘corporation’: 8, ‘made’: 9, ‘money’: 10, ‘georgia’: 11, ‘tech’: 12, ‘is’: 13, ‘a’: 14, ‘university’: 15, ‘in’: 16}
4.将5个标签存到tag_to_ix的字典中。
tag_to_ix = {
"B": 0, "I": 1, "O": 2, START_TAG: 3, STOP_TAG: 4}
5.几个实用的小函数
def prepare_sequence(seq, to_ix):
idxs = [to_ix[w] for w in seq] # 将句子”w1 w2 w3”(词序列)[w1,w2,w3..]中的词w转化为在词表中的索引值 to_ix [w]
return torch.tensor(idxs, dtype=torch.long)
def argmax(vec):
# 得到最大的值的索引
_, idx = torch.max(vec, 1)
return idx.item()
def log_sum_exp(vec):
max_score = vec[0, argmax(vec)] # max_score的维度为1
max_score_broadcast = max_score.view(1, -1).expand(1, vec.size()[1]) # 维度为1*5
return max_score + torch.log(torch.sum(torch.exp(vec - max_score_broadcast)))
6.接下来,我们将我们的句子输入到BILSTM-CRF模型,
model = BiLSTM_CRF(len(word_to_ix), tag_to_ix, EMBEDDING_DIM,