使用PyTorch构建基于BERT-BiLSTM-CRF的命名实体识别模型 捕捉文本中的上下文信息和序列标注任务 从数据预处理、模型定义、训练、评估和预测。 - input_ids, attention_mask = inputs["
如何使用PyTorch深度学习框架开发 基于BERT-BiLSTM-CRF的命名实体识别(NER)模型 捕捉文本中的上下文信息和序列标注任务
使用PyTorch构建基于BERT-BiLSTM-CRF的命名实体识别模型,以下文字及代码仅供参考。
文章目录
1. 安装必要的库2. 数据预处理3. 模型定义4. 训练与评估1. 数据预处理示例数据文件 `data.txt`:数据加载和预处理代码示例:
2. 模型定义3. 训练与评估4. 预测5. 运行预测
基于bert-bilstm-crf的中文医学文本命名实体识别。
基于bert-bilstm-crf的命名实体识别,出Python代码,数据集为人民日报命名实体识别数据集,包含三个实体人名(PER)、地名(LOC)和组织名(ORG)
项目采用pytorch深度学习框架开发
1 基于BERT-BiLSTM-CRF的命名实体识别(NER)模型是一个强大的组合,可以有效地捕捉文本中的上下文信息和序列标注任务的需求。以下是如何使用PyTorch深度学习框架开发这样模型的示例代码,包括数据预处理、模型定义、训练和评估。
1. 安装必要的库
首先,确保安装了必要的库:
pip install torch transformers seqeval
seqeval 是一个用于评估序列标注任务(如NER)性能的库。
2. 数据预处理
假设你已经有了人民日报命名实体识别数据集,并且数据格式为每行一个词及其标签,句子间用空行分隔。你需要将这些数据转换为模型可接受的格式。
from transformers import BertTokenizer
import torch
from torch.utils.data import Dataset, DataLoader
class NERDataset(Dataset):
def __init__(self, sentences, labels, tokenizer, label2id, max_len=128):
self.sentences = sentences
self.labels = labels
self.tokenizer = tokenizer
self.label2id = label2id
self.max_len = max_len
def __len__(self):
return len(self.sentences)
def __getitem__(self, idx):
sentence = self.sentences[idx]
labels = self.labels[idx]
inputs = self.tokenizer.encode_plus(sentence, add_special_tokens=True, max_length=self.max_len, padding='max_length', truncation=True)
input_ids, attention_mask = inputs["input_ids"], inputs["attention_mask"]
label_ids = [self.label2id['O']] + [self.label2id[l] for l in labels] + [self.label2id['O']]
label_ids = label_ids[:self.max_len]
if len(label_ids) < self.max_len:
label_ids += [self.label2id['O']] * (self.max_len - len(label_ids))
return {
'input_ids': torch.tensor(input_ids, dtype=torch.long),
'attention_mask': torch.tensor(attention_mask, dtype=torch.long),
'labels': torch.tensor(label_ids, dtype=torch.long)
}
# 示例调用 拼多多帮助力入口
tokenizer = BertTokenizer.from_pretrained('bert-base-chinese')
label2id = {'B-PER': 0, 'I-PER': 1, 'B-LOC': 2, 'I-LOC': 3, 'B-ORG': 4, 'I-ORG': 5, 'O': 6}
dataset = NERDataset(sentences=['我 爱 北京 天安门'], labels=[['O', 'O', 'B-LOC', 'I-LOC']], tokenizer=tokenizer, label2id=label2id)
3. 模型定义
接下来是BERT-BiLSTM-CRF模型的定义:
from torch import nn
from transformers import BertModel
import torchcrf as crf
class BERTBiLSTMCRF(nn.Module):
def __init__(self, hidden_dim, num_labels, bert_name='bert-base-chinese'):
super(BERTBiLSTMCRF, self).__init__()
self.bert = BertModel.from_pretrained(bert_name)
self.lstm = nn.LSTM(bidirectional=True, num_layers=2, input_size=768, hidden_size=hidden_dim, batch_first=True)
self.linear = nn.Linear(hidden_dim*2, num_labels)
self.crf = crf.CRF(num_labels, batch_first=True)
def forward(self, input_ids, attention_mask=None, labels=None):
outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask)
sequence_output = outputs[0]
lstm_output, _ = self.lstm(sequence_output)
emissions = self.linear(lstm_output)
if labels is not None:
loss = -self.crf(emissions, labels, mask=attention_mask.byte(), reduction='mean')
return loss
else:
prediction = self.crf.decode(emissions, mask=attention_mask.byte())
return prediction
4. 训练与评估
编写训练和评估脚本:
from torch.optim import Adam
def train(model, dataloader, optimizer, device):
model.train()
total_loss = 0
for batch in dataloader:
optimizer.zero_grad()
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_mask'].to(device)
labels = batch['labels'].to(device)
loss = model(input_ids, attention_mask=attention_mask, labels=labels)
loss.backward()
optimizer.step()
total_loss += loss.item()
return total_loss / len(dataloader)
def evaluate(model, dataloader, id2label, device):
model.eval()
predictions, true_labels = [], []
with torch.no_grad():
for batch in dataloader:
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_mask'].to(device)
labels = batch['labels'].to('cpu').numpy()
prediction = model(input_ids, attention_mask=attention_mask)
predictions.extend([[id2label[p] for p in pred] for pred in prediction])
true_labels.extend([[id2label[l] for l in lab if l != -100] for lab in labels])
from seqeval.metrics import classification_report
print(classification_report(true_labels, predictions))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = BERTBiLSTMCRF(hidden_dim=256, num_labels=len(label2id)).to(device)
optimizer = Adam(model.parameters(), lr=3e-5)
train_dataloader = DataLoader(dataset, batch_size=16, shuffle=True)
evaluate_dataloader = DataLoader(evaluate_dataset, batch_size=16)
for epoch in range(epochs):
print(f"Epoch {epoch + 1}/{epochs}")
loss = train(model, train_dataloader, optimizer, device)
print(f"Training Loss: {loss}")
evaluate(model, evaluate_dataloader, id2label={v: k for k, v in label2id.items()}, device=device)
以上就是使用PyTorch构建基于BERT-BiLSTM-CRF的命名实体识别模型的完整流程。请根据你的具体需求调整参数和数据处理逻辑。
基于BERT-BiLSTM-CRF的命名实体识别(NER)项目的框架。为了帮助你更好地理解和使用这个项目,我将提供一些关键代码片段和说明,包括数据预处理、模型定义、训练、预测等部分。
1. 数据预处理
首先,确保你的数据集已经准备好,并且按照标准格式存储。假设你的数据集是文本文件,每行包含一个词及其标签。
示例数据文件 data.txt:
北京 B-LOC
颐和园 I-LOC
觉得 O
还不错 O
。
O
数据加载和预处理代码示例:
from transformers import BertTokenizer
import torch
from torch.utils.data import Dataset, DataLoader
class NERDataset(Dataset):
def __init__(self, sentences, labels, tokenizer, label2id, max_len=128):
self.sentences = sentences
self.labels = labels
self.tokenizer = tokenizer
self.label2id = label2id
self.max_len = max_len
def __len__(self):
return len(self.sentences)
def __getitem__(self, idx):
sentence = self.sentences[idx]
labels = self.labels[idx]
inputs = self.tokenizer.encode_plus(sentence, add_special_tokens=True, max_length=self.max_len, padding='max_length', truncation=True)
input_ids, attention_mask = inputs["input_ids"], inputs["attention_mask"]
label_ids = [self.label2id['O']] + [self.label2id[l] for l in labels] + [self.label2id['O']]
label_ids = label_ids[:self.max_len]
if len(label_ids) < self.max_len:
label_ids += [self.label2id['O']] * (self.max_len - len(label_ids))
return {
'input_ids': torch.tensor(input_ids, dtype=torch.long),
'attention_mask': torch.tensor(attention_mask, dtype=torch.long),
'labels': torch.tensor(label_ids, dtype=torch.long)
}
# 示例调用
tokenizer = BertTokenizer.from_pretrained('bert-base-chinese')
label2id = {'B-PER': 0, 'I-PER': 1, 'B-LOC': 2, 'I-LOC': 3, 'B-ORG': 4, 'I-ORG': 5, 'O': 6}
sentences = ["今天去了北京颐和园,觉得还不错。"]
labels = [["O", "O", "B-LOC", "I-LOC", "O", "O", "O"]]
dataset = NERDataset(sentences, labels, tokenizer, label2id)
2. 模型定义
接下来是BERT-BiLSTM-CRF模型的定义:
from torch import nn
from transformers import BertModel
import torchcrf as crf
class BERTBiLSTMCRF(nn.Module):
def __init__(self, hidden_dim, num_labels, bert_name='bert-base-chinese'):
super(BERTBiLSTMCRF, self).__init__()
self.bert = BertModel.from_pretrained(bert_name)
self.lstm = nn.LSTM(bidirectional=True, num_layers=2, input_size=768, hidden_size=hidden_dim, batch_first=True)
self.linear = nn.Linear(hidden_dim*2, num_labels)
self.crf = crf.CRF(num_labels, batch_first=True)
def forward(self, input_ids, attention_mask=None, labels=None):
outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask)
sequence_output = outputs[0]
lstm_output, _ = self.lstm(sequence_output)
emissions = self.linear(lstm_output)
if labels is not None:
loss = -self.crf(emissions, labels, mask=attention_mask.byte(), reduction='mean')
return loss
else:
prediction = self.crf.decode(emissions, mask=attention_mask.byte())
return prediction
3. 训练与评估
编写训练和评估脚本:
from torch.optim import Adam
def train(model, dataloader, optimizer, device):
model.train()
total_loss = 0
for batch in dataloader:
optimizer.zero_grad()
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_mask'].to(device)
labels = batch['labels'].to(device)
loss = model(input_ids, attention_mask=attention_mask, labels=labels)
loss.backward()
optimizer.step()
total_loss += loss.item()
return total_loss / len(dataloader)
def evaluate(model, dataloader, id2label, device):
model.eval()
predictions, true_labels = [], []
with torch.no_grad():
for batch in dataloader:
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_mask'].to(device)
labels = batch['labels'].to('cpu').numpy()
prediction = model(input_ids, attention_mask=attention_mask)
predictions.extend([[id2label[p] for p in pred] for pred in prediction])
true_labels.extend([[id2label[l] for l in lab if l != -100] for lab in labels])
from seqeval.metrics import classification_report
print(classification_report(true_labels, predictions))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = BERTBiLSTMCRF(hidden_dim=256, num_labels=len(label2id)).to(device)
optimizer = Adam(model.parameters(), lr=3e-5)
train_dataloader = DataLoader(dataset, batch_size=16, shuffle=True)
evaluate_dataloader = DataLoader(evaluate_dataset, batch_size=16)
for epoch in range(epochs):
print(f"Epoch {epoch + 1}/{epochs}")
loss = train(model, train_dataloader, optimizer, device)
print(f"Training Loss: {loss}")
evaluate(model, evaluate_dataloader, id2label={v: k for k, v in label2id.items()}, device=device)
4. 预测
编写预测脚本:
def predict(model, tokenizer, text, device):
model.eval()
inputs = tokenizer.encode_plus(text, add_special_tokens=True, max_length=128, padding='max_length', truncation=True)
input_ids, attention_mask = inputs["input_ids"], inputs["attention_mask"]
input_ids = torch.tensor([input_ids], dtype=torch.long).to(device)
attention_mask = torch.tensor([attention_mask], dtype=torch.long).to(device)
prediction = model(input_ids, attention_mask=attention_mask)
return prediction
text = "今天去了北京颐和园,觉得还不错。"
prediction = predict(model, tokenizer, text, device)
print(prediction)
5. 运行预测
在 predict.py 文件中运行预测代码:
if __name__ == "__main__":
text = "今天去了北京颐和园,觉得还不错。"
word2id = get_vocab()
input = torch.tensor([[word2id.get(w, WORD_UNK_ID) for w in text]])
tokenizer = BertTokenizer.from_pretrained(BERT_MODEL)
prediction = predict(model, tokenizer, text, device)
print(prediction)
以上代码提供了完整的BERT-BiLSTM-CRF模型的实现流程,包括数据预处理、模型定义、训练、评估和预测。
使用PyTorch构建基于BERT-BiLSTM-CRF的命名实体识别模型 捕捉文本中的上下文信息和序列标注任务 从数据预处理、模型定义、训练、评估和预测。
好文推荐