24 KiB
24 KiB
Ekstrakcja informacji
11. NER RNN [ćwiczenia]
Jakub Pokrywka (2021)
Podejście softmax z embeddingami na przykładzie NER
import numpy as np
import gensim
import torch
import pandas as pd
import seaborn as sns
from sklearn.model_selection import train_test_split
from datasets import load_dataset
import torchtext
#from torchtext.vocab import vocab
from collections import Counter
from sklearn.datasets import fetch_20newsgroups
# https://scikit-learn.org/0.19/datasets/twenty_newsgroups.html
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import accuracy_score
from tqdm.notebook import tqdm
import torch
dataset = load_dataset("conll2003")
Reusing dataset conll2003 (/home/kuba/.cache/huggingface/datasets/conll2003/conll2003/1.0.0/63f4ebd1bcb7148b1644497336fd74643d4ce70123334431a3c053b7ee4e96ee)
0%| | 0/3 [00:00<?, ?it/s]
def build_vocab(dataset):
counter = Counter()
for document in dataset:
counter.update(document)
vocab = torchtext.vocab.vocab(counter, specials=['<unk>', '<pad>', '<bos>', '<eos>'])
vocab.set_default_index(0)
return vocab
vocab = build_vocab(dataset['train']['tokens'])
vocab['on']
21
def data_process(dt):
return [ torch.tensor([vocab['<bos>']] +[vocab[token] for token in document ] + [vocab['<eos>']], dtype = torch.long) for document in dt]
def labels_process(dt):
return [ torch.tensor([0] + document + [0], dtype = torch.long) for document in dt]
train_tokens_ids = data_process(dataset['train']['tokens'])
test_tokens_ids = data_process(dataset['test']['tokens'])
validation_tokens_ids = data_process(dataset['validation']['tokens'])
train_labels = labels_process(dataset['train']['ner_tags'])
validation_labels = labels_process(dataset['validation']['ner_tags'])
test_labels = labels_process(dataset['test']['ner_tags'])
train_tokens_ids[0]
tensor([ 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 3])
dataset['train'][0]
{'id': '0', 'tokens': ['EU', 'rejects', 'German', 'call', 'to', 'boycott', 'British', 'lamb', '.'], 'pos_tags': [22, 42, 16, 21, 35, 37, 16, 21, 7], 'chunk_tags': [11, 21, 11, 12, 21, 22, 11, 12, 0], 'ner_tags': [3, 0, 7, 0, 0, 0, 7, 0, 0]}
train_labels[0]
tensor([0, 3, 0, 7, 0, 0, 0, 7, 0, 0, 0])
def get_scores(y_true, y_pred):
acc_score = 0
tp = 0
fp = 0
selected_items = 0
relevant_items = 0
for p,t in zip(y_pred, y_true):
if p == t:
acc_score +=1
if p > 0 and p == t:
tp +=1
if p > 0:
selected_items += 1
if t > 0 :
relevant_items +=1
if selected_items == 0:
precision = 1.0
else:
precision = tp / selected_items
if relevant_items == 0:
recall = 1.0
else:
recall = tp / relevant_items
if precision + recall == 0.0 :
f1 = 0.0
else:
f1 = 2* precision * recall / (precision + recall)
return precision, recall, f1
num_tags = max([max(x) for x in dataset['train']['ner_tags'] if x]) + 1
class LSTM(torch.nn.Module):
def __init__(self):
super(LSTM, self).__init__()
self.emb = torch.nn.Embedding(len(vocab.get_itos()),100)
self.rec = torch.nn.LSTM(100, 256, 1, batch_first = True)
self.fc1 = torch.nn.Linear( 256 , 9)
def forward(self, x):
emb = torch.relu(self.emb(x))
lstm_output, (h_n, c_n) = self.rec(emb)
out_weights = self.fc1(lstm_output)
return out_weights
lstm = LSTM()
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(lstm.parameters())
def eval_model(dataset_tokens, dataset_labels, model):
Y_true = []
Y_pred = []
for i in tqdm(range(len(dataset_labels))):
batch_tokens = dataset_tokens[i].unsqueeze(0)
tags = list(dataset_labels[i].numpy())
Y_true += tags
Y_batch_pred_weights = model(batch_tokens).squeeze(0)
Y_batch_pred = torch.argmax(Y_batch_pred_weights,1)
Y_pred += list(Y_batch_pred.numpy())
return get_scores(Y_true, Y_pred)
NUM_EPOCHS = 5
for i in range(NUM_EPOCHS):
lstm.train()
for i in tqdm(range(500)):
#for i in tqdm(range(len(train_labels))):
batch_tokens = train_tokens_ids[i].unsqueeze(0)
tags = train_labels[i].unsqueeze(1)
predicted_tags = lstm(batch_tokens)
optimizer.zero_grad()
loss = criterion(predicted_tags.squeeze(0),tags.squeeze(1))
loss.backward()
optimizer.step()
lstm.eval()
print(eval_model(validation_tokens_ids, validation_labels, lstm))
0%| | 0/500 [00:00<?, ?it/s]
0%| | 0/3251 [00:00<?, ?it/s]
(0.2310126582278481, 0.02545623619667558, 0.04585907234844519)
0%| | 0/500 [00:00<?, ?it/s]
0%| | 0/3251 [00:00<?, ?it/s]
(0.22903453136011276, 0.15111007787980937, 0.1820855802227047)
0%| | 0/500 [00:00<?, ?it/s]
0%| | 0/3251 [00:00<?, ?it/s]
(0.22289679098005205, 0.20911310008136696, 0.21578505457598657)
0%| | 0/500 [00:00<?, ?it/s]
0%| | 0/3251 [00:00<?, ?it/s]
(0.2553244180287271, 0.23968383122166687, 0.2472570297979495)
0%| | 0/500 [00:00<?, ?it/s]
0%| | 0/3251 [00:00<?, ?it/s]
(0.26687507236308905, 0.2679297919330466, 0.26740139211136893)
eval_model(validation_tokens_ids, validation_labels, lstm)
0%| | 0/3251 [00:00<?, ?it/s]
(0.26687507236308905, 0.2679297919330466, 0.26740139211136893)
eval_model(test_tokens_ids, test_labels, lstm)
0%| | 0/3454 [00:00<?, ?it/s]
(0.2493934363427404, 0.24075443786982248, 0.24499780467916954)
len(train_tokens_ids)
14042
pytania
- co zrobić z trenowaniem na batchach > 1 ?
- co zrobić, żeby sieć uwzględniała następne tokeny, a nie tylko poprzednie?
- w jaki sposób wykorzystać taką sieć do zadania zwykłej klasyfikacji?
Zadanie na zajęcia ( 20 minut)
zmodyfikować sieć tak, żeby była używała dwuwarstwowej, dwukierunkowej warstwy GRU oraz dropoutu. Dropout ma nałożony na embeddingi.
class GRU(torch.nn.Module):
def __init__(self):
super(GRU, self).__init__()
self.emb = torch.nn.Embedding(len(vocab.get_itos()),100)
self.dropout = torch.nn.Dropout(0.2)
self.rec = torch.nn.GRU(100, 256, 2, batch_first = True, bidirectional = True)
self.fc1 = torch.nn.Linear(2* 256 , 9)
def forward(self, x):
emb = torch.relu(self.emb(x))
emb = self.dropout(emb)
gru_output, h_n = self.rec(emb)
out_weights = self.fc1(gru_output)
return out_weights
gru = GRU()
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(gru.parameters())
NUM_EPOCHS = 5
for i in range(NUM_EPOCHS):
gru.train()
for i in tqdm(range(500)):
#for i in tqdm(range(len(train_labels))):
batch_tokens = train_tokens_ids[i].unsqueeze(0)
tags = train_labels[i].unsqueeze(1)
predicted_tags = gru(batch_tokens)
optimizer.zero_grad()
loss = criterion(predicted_tags.squeeze(0),tags.squeeze(1))
loss.backward()
optimizer.step()
gru.eval()
print(eval_model(validation_tokens_ids, validation_labels, gru))
0%| | 0/500 [00:00<?, ?it/s]
0%| | 0/3251 [00:00<?, ?it/s]
(0.38776758409785933, 0.14739044519353714, 0.2135938684410006)
0%| | 0/500 [00:00<?, ?it/s]
0%| | 0/3251 [00:00<?, ?it/s]
(0.27651183172655563, 0.22003952109729163, 0.24506440546313676)
0%| | 0/500 [00:00<?, ?it/s]
0%| | 0/3251 [00:00<?, ?it/s]
(0.31285223367697595, 0.2645588748111124, 0.28668598060209094)
0%| | 0/500 [00:00<?, ?it/s]
0%| | 0/3251 [00:00<?, ?it/s]
(0.2596728376922323, 0.3081483203533651, 0.2818413778439294)
0%| | 0/500 [00:00<?, ?it/s]
0%| | 0/3251 [00:00<?, ?it/s]
(0.29086115992970124, 0.30779960478902707, 0.29909075506861693)
Zadanie domowe
- stworzyć model seq labelling bazujący na sieci neuronowej opisanej w punkcie niżej (można bazować na tym jupyterze lub nie).
- model sieci to GRU (o dowolnych parametrach) + CRF w pytorchu korzystając z modułu CRF z poprzednich zajęć- - stworzyć predykcje w plikach dev-0/out.tsv oraz test-A/out.tsv
- wynik fscore sprawdzony za pomocą narzędzia geval (patrz poprzednie zadanie) powinien wynosić conajmniej 0.65 termin 22.06, 60 punktów, za najlepszy wynik- 100 punktów