Для тренировки Squad_BERT модели на вашем собственном датасете необходимо выполнить следующие шаги:
- Загрузите датасет с помощью Python-библиотеки Pandas или любого другого инструмента, который вы предпочитаете использовать для обработки данных.
import pandas as pd
df_train = pd.read_csv('train.csv')
df_dev = pd.read_csv('dev.csv')
- Предобработка данных: чтобы преобразовать данные в формат, пригодный для обучения модели, необходимо применить методы предобработки данных, которые обычно включают в себя токенизацию текста, разбиение его на токены, преобразование токенов в числа и так далее.
from transformers import BertTokenizer
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
def preprocess_data(data_frame):
contexts, questions, answers = [], [], []
for index, row in data_frame.iterrows():
context, question, answer_text = row[0], row[1], row[2]
if type(answer_text) != str:
continue
start_char_idx = context.find(answer_text)
end_char_idx = start_char_idx + len(answer_text)
if start_char_idx == -1:
continue
token_start_idx = 0
while token_start_idx < len(context):
token_end_idx = token_start_idx + len(tokenizer.tokenize(context[token_start_idx:]))
if start_char_idx >= token_start_idx and end_char_idx <= token_end_idx:
break
token_start_idx = token_end_idx + 1
token_end_idx = 0
while token_end_idx < len(context):
tmp_end_idx = token_end_idx + len(tokenizer.tokenize(context[token_end_idx:]))
if end_char_idx <= tmp_end_idx:
break
token_end_idx = tmp_end_idx + 1
context_tokens = tokenizer.tokenize(context)
answer_tokens = tokenizer.tokenize(answer_text)
answer_token_start_idx = 0
while context_tokens[token_start_idx:token_end_idx+1].count(answer_tokens[answer_token_start_idx]) != 1:
answer_token_start_idx += 1
answer_token_end_idx = len(answer_tokens) - 1
while context_tokens[token_start_idx:token_end_idx+1].count(answer_tokens[answer_token_end_idx]) != 1:
answer_token_end_idx -= 1
tokenized_context = tokenizer.encode(context, truncation=True, padding=True, max_length=512)
tokenized_question = tokenizer.encode(question, truncation=True, padding=True, max_length=32)
tokenized_answer = tokenizer.encode(answer_text, truncation=True, padding=True, max_length=32)
input_ids = tokenized_context
attention_mask = [1] * len(input_ids)
token_type_ids = [0] * (len(tokenized_question) + 2) + [1] * (len(input_ids) - len(tokenized_question) - 2)
start_token_idx = token_start_idx + len(tokenized_question) + 2
end_token_idx = token_end_idx + len(tokenized_question) + 2
if start_token_idx >= 512 or end_token_idx >= 512:
continue
outputs = {
'input_ids': input_ids,
'attention_mask': attention_mask,
'token_type_ids': token_type_ids,
'start_token_idx': start_token_idx,
'end_token_idx': end_token_idx,
'tokenized_question': tokenized_question,
'tokenized_answer': tokenized_answer,
'context': context,
'question': question,
'answer': answer_text
}
contexts.append(context)
questions.append(question)
answers.append(answer_text)
return contexts, questions, answers, outputs
train_contexts, train_questions, train_answers, train_outputs = preprocess_data(df_train)
dev_contexts, dev_questions, dev_answers, dev_outputs = preprocess_data(df_dev)
- Создайте класс датасета, пригодный для обучения модели.
import torch
from torch.utils.data import Dataset
class CustomDataset(Dataset):
def __init__(self, contexts, questions, answers, outputs):
self.contexts = contexts
self.questions = questions
self.answers = answers
self.outputs = outputs
def __len__(self):
return len(self.outputs)
def __getitem__(self, index):
input_ids = torch.tensor(self.outputs[index]['input_ids'], dtype=torch.long)
attention_mask = torch.tensor(self.outputs[index]['attention_mask'], dtype=torch.long)
token_type_ids = torch.tensor(self.outputs[index]['token_type_ids'], dtype=torch.long)
start_token_idx = torch.tensor(self.outputs[index]['start_token_idx'], dtype=torch.long)
end_token_idx = torch.tensor(self.outputs[index]['end_token_idx'], dtype=torch.long)
item = {
'input_ids': input_ids,
'attention_mask': attention_mask,
'token_type_ids': token_type_ids,
'start_token_idx': start_token_idx,
'end_token_idx': end_token_idx
}
return item
- Определите модель и загрузите веса предобученной модели BERT.
from transformers import BertModel
class BertQA(nn.Module):
def __init__(self):
super().__init__()
self.bert = BertModel.from_pretrained('bert-base-uncased')
self.dropout = nn.Dropout(0.1)
self.classifier = nn.Linear(self.bert.config.hidden_size, 2)
nn.init.normal_(self.classifier.weight, std=0.02)
nn.init.normal_(self.classifier.bias, 0)
def forward(self, input_ids, attention_mask, token_type_ids):
bert_outputs = self.bert(input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)
last_hidden_state = bert_outputs.last_hidden_state
pooled_output = bert_outputs.pooler_output
x = self.dropout(pooled_output)
outputs = self.classifier(x)
start_logits, end_logits = outputs.split(1, dim=-1)
start_logits = start_logits.squeeze(-1)
end_logits = end_logits.squeeze(-1)
return start_logits, end_logits
model = BertQA()
- Обучите вашу модель.
from torch.utils.data import DataLoader
from transformers import AdamW
import numpy as np
def train_model(model, dataloader, optimizer, device='cpu'):
model.train()
loss_fn = nn.CrossEntropyLoss()
losses = []
for batch in dataloader:
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_mask'].to(device)
token_type_ids = batch['token_type_ids'].to(device)
start_token_idx = batch['start_token_idx'].to(device)
end_token_idx = batch['end_token_idx'].to(device)
optimizer.zero_grad()
start_logits, end_logits = model(input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)
loss = (loss_fn(start_logits, start_token_idx) + loss_fn(end_logits, end_token_idx)) / 2
loss.backward()
optimizer.step()
losses.append(loss.item())
return np.mean(losses)
optimizer = AdamW(model.parameters(), lr=0.0001)
train_dataset = CustomDataset(train_contexts, train_questions, train_answers, train_outputs)
train_loader = DataLoader(train_dataset, batch_size=16, shuffle=True)
dev_dataset = CustomDataset(dev_contexts, dev_questions, dev_answers, dev_outputs)
dev_loader = DataLoader(dev_dataset, batch_size=16, shuffle=False)
for epoch in range(3):
print(f'Epoch: {epoch}')
train_loss = train_model(model, train_loader, optimizer, device='cuda')
print(f'Train loss: {train_loss:.4f}')
- Оцените качество своей модели.
def evaluate_model(model, dataloader, device='cpu'):
model.eval()
pred_start_logits = []
pred_end_logits = []
true_start_token_idx = []
true_end_token_idx = []
with torch.no_grad():
for batch in dataloader:
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_mask'].to(device)
token_type_ids = batch['token_type_ids'].to(device)
start_token_idx = batch['start_token_idx'].to(device)
end_token_idx = batch['end_token_idx'].to(device)
start_logits, end_logits = model(input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)
pred_start_logits.extend(start_logits.cpu().detach().numpy().tolist())
pred_end_logits.extend(end_logits.cpu().detach().numpy().tolist())
true_start_token_idx.extend(start_token_idx.cpu().detach().numpy().tolist())
true_end_token_idx.extend(end_token_idx.cpu().detach().numpy().tolist())
pred_start_token_idx = np.argmax(pred_start_logits, axis=-1)
pred_end_token_idx = np.argmax(pred_end_logits, axis=-1)
start_token_f1 = f1_score(true_start_token_idx, pred_start_token_idx, average='macro')
end_token_f1 = f1_score(true_end_token_idx, pred_end_token_idx, average='macro')
exact_match = metric_max_over_ground_truths(exact_match_score, preds, truths)
f1 = metric_max_over_ground_truths(f1_score, preds, truths)
print(f'Exact match: {exact_match:.4f}; F1: {f1:.4f}; Start Token F1: {start_token_f1:.4f}; End Token F1: {end_token_f1:.4f}')
evaluate_model(model, dev_loader, device='cuda')
После завершения обучения и оценки качества модели, можно использовать ее для предсказания ответов на новые вопросы.