en-ner-conll-2003/rnn_fras-Copy1.ipynb

20 KiB
Raw Blame History

Zadanie domowe

  • sklonować repozytorium https://git.wmi.amu.edu.pl/kubapok/en-ner-conll-2003
  • 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
  • proszę umieścić predykcję oraz skrypty generujące (w postaci tekstowej a nie jupyter) w repo, a w MS TEAMS umieścić link do swojego repo termin 22.06, 60 punktów, za najlepszy wynik- 100 punktów
import numpy as np
import torch
from torchtext.vocab import Vocab
from collections import Counter
from tqdm.notebook import tqdm
import lzma
import itertools
from torchcrf import CRF
def read_data(filename):
    all_data = lzma.open(filename).read().decode('UTF-8').split('\n')
    return [line.split('\t') for line in all_data][:-1]
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]
def build_vocab(dataset):
    counter = Counter()
    for document in dataset:
        counter.update(document)
    return Vocab(counter, specials=['<unk>', '<pad>', '<bos>', '<eos>'])
train_data = read_data('train/train.tsv.xz')

tokens, ner_tags = [], []
for i in train_data:
    ner_tags.append(i[0].split())
    tokens.append(i[1].split())
vocab = build_vocab(tokens)
train_tokens_ids = data_process(tokens)
ner_tags_set = list(set(itertools.chain(*ner_tags)))
ner_tags_set.sort()
print(ner_tags_set)
train_labels = labels_process([[ner_tags_set.index(token) for token in doc] for doc in ner_tags])
['B-LOC', 'B-MISC', 'B-ORG', 'B-PER', 'I-LOC', 'I-MISC', 'I-ORG', 'I-PER', 'O']
num_tags = max([max(x) for x in train_labels]) + 1 
class GRU(torch.nn.Module):

    def __init__(self):
        super(GRU, self).__init__()
        self.emb = torch.nn.Embedding(len(vocab.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
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
def eval_model(dataset_tokens, dataset_labels, model):
    Y_true = []
    Y_pred = []
    gru.eval()
    crf.eval()
    for i in tqdm(range(len(dataset_labels))):
        batch_tokens = dataset_tokens[i]
        tags = list(dataset_labels[i].numpy())
        emissions = ff(batch_tokens).unsqueeze(1)
        Y_pred += crf.decode(emissions)[0]
        Y_true += tags
    return get_scores(Y_true, Y_pred)
gru = GRU()
crf = CRF(num_tags)
params = list(gru.parameters()) + list(crf.parameters())
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(params)
NUM_EPOCHS = 2
for i in range(NUM_EPOCHS):
    gru.train()
    crf.train()
    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  = -crf(predicted_tags.unsqueeze(1),tags.squeeze(1))
        loss.backward()
        optimizer.step()
    gru.eval()
    crf.eval()
    print(eval_model(train_tokens_ids, train_labels, gru))
HBox(children=(FloatProgress(value=0.0, max=945.0), HTML(value='')))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-77-3305460cbe70> in <module>
      7         predicted_tags = gru(batch_tokens)
      8         optimizer.zero_grad()
----> 9         loss  = -crf(predicted_tags.unsqueeze(1),tags.squeeze(1))
     10         loss.backward()
     11         optimizer.step()

~/.local/lib/python3.8/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1049         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1050                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1051             return forward_call(*input, **kwargs)
   1052         # Do not call functions when jit is used
   1053         full_backward_hooks, non_full_backward_hooks = [], []

~/.local/lib/python3.8/site-packages/torchcrf/__init__.py in forward(self, emissions, tags, mask, reduction)
     88             reduction is ``none``, ``()`` otherwise.
     89         """
---> 90         self._validate(emissions, tags=tags, mask=mask)
     91         if reduction not in ('none', 'sum', 'mean', 'token_mean'):
     92             raise ValueError(f'invalid reduction: {reduction}')

~/.local/lib/python3.8/site-packages/torchcrf/__init__.py in _validate(self, emissions, tags, mask)
    145             mask: Optional[torch.ByteTensor] = None) -> None:
    146         if emissions.dim() != 3:
--> 147             raise ValueError(f'emissions must have dimension of 3, got {emissions.dim()}')
    148         if emissions.size(2) != self.num_tags:
    149             raise ValueError(

ValueError: emissions must have dimension of 3, got 4

dev-0

def predict_labels(dataset_tokens, model):
    Y_true = []
    Y_pred = []
    result = []
    for i in tqdm(range(len(dataset_tokens))):
        batch_tokens = dataset_tokens[i].unsqueeze(0)
        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())
        result += [list(Y_batch_pred.numpy())]
    return result
with open('dev-0/in.tsv', "r", encoding="utf-8") as f:
    dev_0_data = [line.rstrip() for line in f]
    
dev_0_data = [i.split() for i in dev_0_data]
dev_0_tokens_ids = data_process(dev_0_data)
with open('dev-0/expected.tsv', "r", encoding="utf-8") as f:
    dev_0_labels = [line.rstrip() for line in f]
    
dev_0_labels = [i.split() for i in dev_0_labels]
dev_0_labels = labels_process([[ner_tags_set.index(token) for token in doc] for doc in dev_0_labels])
tmp = predict_labels(dev_0_tokens_ids, gru)
HBox(children=(FloatProgress(value=0.0, max=215.0), HTML(value='')))
r = [[ner_tags_set[i] for i in tmp2] for tmp2 in tmp]
# for doc in r:
#     if doc[0] != 'O':
#         doc[0] = 'B' + doc[0][1:]
#     for i in range(len(doc))[:-1]:
#         if doc[i] == 'O':
#             if doc[i + 1] != 'O':
#                 doc[i + 1] = 'B' + doc[i + 1][1:]
#         elif doc[i + 1] != 'O':
#             if doc[i][1:] == doc[i + 1][1:]:
#                 doc[i + 1] = 'I' + doc[i + 1][1:]
#             else:
#                 doc[i + 1] = 'B' + doc[i + 1][1:]
f = open("dev-0/out.tsv", "a")
for i in r:
    f.write(' '.join(i) + '\n')
f.close()

test-A

with open('test-A/in.tsv', "r", encoding="utf-8") as f:
    test_A_data = [line.rstrip() for line in f]
    
test_A_data = [i.split() for i in test_A_data]
test_A_tokens_ids = data_process(test_A_data)
tmp = predict_labels(dev_0_tokens_ids, gru)
r = [[ner_tags_set[i] for i in tmp2] for tmp2 in tmp]
for doc in r:
    if doc[0] != 'O':
        doc[0] = 'B' + doc[0][1:]
    for i in range(len(doc))[:-1]:
        if doc[i] == 'O':
            if doc[i + 1] != 'O':
                doc[i + 1] = 'B' + doc[i + 1][1:]
        elif doc[i + 1] != 'O':
            if doc[i][1:] == doc[i + 1][1:]:
                doc[i + 1] = 'I' + doc[i + 1][1:]
            else:
                doc[i + 1] = 'B' + doc[i + 1][1:]
HBox(children=(FloatProgress(value=0.0, max=215.0), HTML(value='')))
f = open("test-A/out.tsv", "a")
for i in r:
    f.write(' '.join(i) + '\n')
f.close()