BiSTM_CRF中文分词代码实现
时间: 2023-07-24 18:45:02 浏览: 121
以下是一个简单的BiLSTM-CRF中文分词的代码实现,使用Python和PyTorch框架:
```python
import torch
import torch.nn as nn
import torch.optim as optim
# 定义BiLSTM-CRF模型
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_embeddings = nn.Embedding(vocab_size, embedding_dim)
# 定义双向LSTM层
self.lstm = nn.LSTM(embedding_dim, hidden_dim // 2, num_layers=1, bidirectional=True)
# 定义全连接层
self.hidden2tag = nn.Linear(hidden_dim, self.tagset_size)
# 定义转移矩阵
self.transitions = nn.Parameter(torch.randn(self.tagset_size, self.tagset_size))
# 定义开始和结束的标记
self.start_tag = torch.tensor([tag_to_ix['<START>']], dtype=torch.long)
self.end_tag = torch.tensor([tag_to_ix['<END>']], dtype=torch.long)
# 初始化参数
nn.init.xavier_uniform_(self.transitions)
def _forward_alg(self, feats):
# 初始化alpha值
init_alphas = torch.full((1, self.tagset_size), -10000.)
init_alphas[0][self.tag_to_ix['<START>']] = 0.
# 转换为张量
forward_var = init_alphas
# 迭代每个词的特征
for feat in feats:
alphas_t = []
for next_tag in range(self.tagset_size):
emit_score = feat[next_tag].view(1, -1).expand(1, self.tagset_size)
trans_score = self.transitions[next_tag].view(1, -1)
next_tag_var = forward_var + trans_score + emit_score
alphas_t.append(self._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['<END>']]
alpha = self._log_sum_exp(terminal_var)
return alpha
def _score_sentence(self, feats, tags):
# 计算序列得分
score = torch.zeros(1)
tags = torch.cat([self.start_tag, 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['<END>'], tags[-1]]
return score
def _viterbi_decode(self, feats):
backpointers = []
# 初始化viterbi变量
init_vvars = torch.full((1, self.tagset_size), -10000.)
init_vvars[0][self.tag_to_ix['<START>']] = 0
# 迭代每个词的特征
forward_var = init_vvars
for feat in feats:
bptrs_t = []
viterbivars_t = []
for next_tag in range(self.tagset_size):
next_tag_var = forward_var + self.transitions[next_tag]
best_tag_id = self._argmax(next_tag_var)
bptrs_t.append(best_tag_id)
viterbivars_t.append(next_tag_var[0][best_tag_id].view(1))
forward_var = (torch.cat(viterbivars_t) + feat).view(1, -1)
backpointers.append(bptrs_t)
# 最后添加结束标记
terminal_var = forward_var + self.transitions[self.tag_to_ix['<END>']]
best_tag_id = self._argmax(terminal_var)
path_score = terminal_var[0][best_tag_id]
# 回溯路径
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)
start = best_path.pop()
assert start == self.tag_to_ix['<START>']
best_path.reverse()
return path_score, best_path
def _log_sum_exp(self, vec):
# 计算log-sum-exp
max_score = vec[0, self._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)))
def _argmax(self, vec):
# 返回最大值的下标
_, idx = torch.max(vec, 1)
return idx.item()
def neg_log_likelihood(self, sentence, tags):
# 计算负对数似然损失
self.hidden = self.init_hidden()
embeds = self.word_embeddings(sentence)
lstm_out, _ = self.lstm(embeds.view(len(sentence), 1, -1))
lstm_out = lstm_out.view(len(sentence), self.hidden_dim)
lstm_feats = self.hidden2tag(lstm_out)
forward_score = self._forward_alg(lstm_feats)
gold_score = self._score_sentence(lstm_feats, tags)
return forward_score - gold_score
def forward(self, sentence):
# 预测标签
self.hidden = self.init_hidden()
embeds = self.word_embeddings(sentence)
lstm_out, _ = self.lstm(embeds.view(len(sentence), 1, -1))
lstm_out = lstm_out.view(len(sentence), self.hidden_dim)
lstm_feats = self.hidden2tag(lstm_out)
score, tag_seq = self._viterbi_decode(lstm_feats)
return score, tag_seq
def init_hidden(self):
# 初始化LSTM隐藏层
return (torch.randn(2, 1, self.hidden_dim // 2),
torch.randn(2, 1, self.hidden_dim // 2))
# 定义标签和词汇表
START_TAG = "<START>"
END_TAG = "<END>"
tag_to_ix = {START_TAG: 0, "B": 1, "I": 2, "O": 3, END_TAG: 4}
ix_to_tag = {v: k for k, v in tag_to_ix.items()}
vocab_size = len(word_to_ix)
# 定义模型和优化器
model = BiLSTM_CRF(vocab_size, tag_to_ix, EMBEDDING_DIM, HIDDEN_DIM)
optimizer = optim.SGD(model.parameters(), lr=0.01, weight_decay=1e-4)
# 训练模型
for epoch in range(300):
for sentence, tags in training_data:
# 清空梯度
model.zero_grad()
# 转换为张量
sentence_in = prepare_sequence(sentence, word_to_ix)
targets = torch.tensor([tag_to_ix[t] for t in tags], dtype=torch.long)
# 计算损失函数并更新模型
loss = model.neg_log_likelihood(sentence_in, targets)
loss.backward()
optimizer.step()
# 测试模型
with torch.no_grad():
precheck_sent = prepare_sequence(test_data[0][0], word_to_ix)
print(model(precheck_sent))
```
阅读全文