aitech-eks-pub-22/cw/11_NER_RNN_ODPOWIEDZI.ipynb
Jakub Pokrywka 86915640a6 11
2022-06-07 15:50:27 +02:00

24 KiB

Logo 1

Ekstrakcja informacji

11. NER RNN [ćwiczenia]

Jakub Pokrywka (2021)

Logo 2

Podejście softmax z embeddingami na przykładzie NER

import numpy as np
import torch
import pandas as pd

from datasets import load_dataset
import torchtext
#from torchtext.vocab import vocab
from collections import Counter


from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import accuracy_score

from tqdm.notebook import tqdm

import torch
device = 'cpu'
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().to(device)
criterion = torch.nn.CrossEntropyLoss().to(device)
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).to(device)
        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.cpu().numpy())
        

    return get_scores(Y_true, Y_pred)
        
NUM_EPOCHS = 5
for i in range(NUM_EPOCHS):
    lstm.train()
    #for i in tqdm(range(5000)):
    for i in tqdm(range(len(train_labels))):
        batch_tokens = train_tokens_ids[i].unsqueeze(0).to(device)
        tags = train_labels[i].unsqueeze(1).to(device)
        
        
        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/14042 [00:00<?, ?it/s]
  0%|          | 0/3251 [00:00<?, ?it/s]
(0.516575591985428, 0.49447867023131464, 0.505285663380449)
  0%|          | 0/14042 [00:00<?, ?it/s]
  0%|          | 0/3251 [00:00<?, ?it/s]
(0.6624173748819642, 0.6523305823549924, 0.6573352855051245)
  0%|          | 0/14042 [00:00<?, ?it/s]
  0%|          | 0/3251 [00:00<?, ?it/s]
(0.7022361255937898, 0.7045216784842496, 0.7033770453754206)
  0%|          | 0/14042 [00:00<?, ?it/s]
  0%|          | 0/3251 [00:00<?, ?it/s]
(0.7282225874618455, 0.7210275485295827, 0.7246072075229251)
  0%|          | 0/14042 [00:00<?, ?it/s]
  0%|          | 0/3251 [00:00<?, ?it/s]
(0.7124554367201426, 0.7433453446472161, 0.7275726719381079)
eval_model(validation_tokens_ids, validation_labels, lstm)
  0%|          | 0/3251 [00:00<?, ?it/s]
(0.7124554367201426, 0.7433453446472161, 0.7275726719381079)
eval_model(test_tokens_ids, test_labels, lstm)
  0%|          | 0/3454 [00:00<?, ?it/s]
(0.6445353594389246, 0.6797337278106509, 0.6616667666646667)
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().to(device)
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).to(device)
        tags = train_labels[i].unsqueeze(1).to(device)
        
        
        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/14042 [00:00<?, ?it/s]
  0%|          | 0/3251 [00:00<?, ?it/s]
(0.6109818520241973, 0.4578635359758224, 0.5234551495016612)
  0%|          | 0/14042 [00:00<?, ?it/s]
  0%|          | 0/3251 [00:00<?, ?it/s]
(0.6290377039954981, 0.6496570963617343, 0.639181152790485)
  0%|          | 0/14042 [00:00<?, ?it/s]
  0%|          | 0/3251 [00:00<?, ?it/s]
(0.6755871725383921, 0.6954550738114611, 0.6853771693682342)
  0%|          | 0/14042 [00:00<?, ?it/s]
  0%|          | 0/3251 [00:00<?, ?it/s]
(0.7477821586988664, 0.7054515866558178, 0.7260003588731384)
  0%|          | 0/14042 [00:00<?, ?it/s]
  0%|          | 0/3251 [00:00<?, ?it/s]
(0.7669533169533169, 0.725677089387423, 0.745744490234725)

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