aitech-eks-pub/cw/12_transformery.ipynb

15 KiB

Logo 1

Ekstrakcja informacji

12. Transformery [ćwiczenia]

Jakub Pokrywka (2021)

Logo 2

bpe

pip install tokenizers

from tokenizers import Tokenizer, models, trainers
from tokenizers.trainers import BpeTrainer
tokenizer = Tokenizer(models.BPE())
trainer = trainers.BpeTrainer(vocab_size=20000, min_frequency=2)
tokenizer.train(files = ['/home/kuba/Syncthing/przedmioty/2020-02/ISI/zajecia9_ngramowy_model_jDDezykowy/pan-tadeusz-train.txt'], trainer = trainer)
output = tokenizer.encode("Nie śpiewają piosenek: pracują leniwo,")
output.ids
output.tokens
tokenizer.save("./my-bpe.tokenizer.json", pretty=True)

ZADANIE

stworzyć BPE tokenizer na podstawie https://git.wmi.amu.edu.pl/kubapok/lalka-lm/src/branch/master/train/train.tsv i stworzyć stokenizowaną listę: https://git.wmi.amu.edu.pl/kubapok/lalka-lm/src/branch/master/test-A/in.tsv

wybrać vocab_size = 8k, uwzględnić dodatkowe tokeny: BOS oraz EOS i wpleść je do zbioru testowego

transformery

# pip install transformers

przykłady pochodzą częściowo z: https://huggingface.co/

import torch
from transformers import pipeline, set_seed
from transformers import RobertaTokenizer, RobertaModel
tokenizer = RobertaTokenizer.from_pretrained('roberta-base')
model = RobertaModel.from_pretrained('roberta-base')
text = "Replace me by any text you'd like. Bla Bla"
encoded_input = tokenizer(text, return_tensors='pt')
encoded_input['input_ids']
encoded_input['input_ids']
tokenizer.decode([162])
output = model(**encoded_input)
output
len(output)
output[0].shape

output[1].shape
output = model(**encoded_input, output_hidden_states=True)
len(output)
len(output[2])
output[2][0]
output[2][0].shape
output[2][1].shape
output[2][12].shape
output = model(**encoded_input, output_attentions=True)
len(output)
len(output[2])
output[2][0].shape
output[2][2]

gotowe api

generowanie tekstu

model = pipeline('text-generation', model='gpt2')
model("Hello, I'm a computer science student", max_length=30, num_return_sequences=5)
model("I want to contribute to Google's Computer Vision Program, which is doing extensive work on big", max_length=30, num_return_sequences=5)

sentiment analysis

from transformers import pipeline

model = pipeline("sentiment-analysis", model='distilbert-base-uncased-finetuned-sst-2-english')
model
model("I'm very happy. Today is the beatifull weather")
model("It's raining. What a terrible day...")

NER

model = pipeline("sentiment-analysis", model='distilbert-base-uncased-finetuned-sst-2-english')
from transformers import pipeline
model = pipeline("ner")
text = "George Washington went to Washington"
model(text)

masked language modelling

ZADANIE (10 minut)

przewidzieć <mask> token w "The world <MASK> II started in 1939"" wg dowolnego anglojęzycznego modelu

text summarization

summarizer = pipeline("summarization")
ARTICLE = """ New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County, New York.
A year later, she got married again in Westchester County, but to a different man and without divorcing her first husband.
Only 18 days after that marriage, she got hitched yet again. Then, Barrientos declared "I do" five more times, sometimes only within two weeks of each other.
In 2010, she married once more, this time in the Bronx. In an application for a marriage license, she stated it was her "first and only" marriage.
Barrientos, now 39, is facing two criminal counts of "offering a false instrument for filing in the first degree," referring to her false statements on the
2010 marriage license application, according to court documents.
Prosecutors said the marriages were part of an immigration scam.
On Friday, she pleaded not guilty at State Supreme Court in the Bronx, according to her attorney, Christopher Wright, who declined to comment further.
After leaving court, Barrientos was arrested and charged with theft of service and criminal trespass for allegedly sneaking into the New York subway through an emergency exit, said Detective
Annette Markowski, a police spokeswoman. In total, Barrientos has been married 10 times, with nine of her marriages occurring between 1999 and 2002.
All occurred either in Westchester County, Long Island, New Jersey or the Bronx. She is believed to still be married to four men, and at one time, she was married to eight men at once, prosecutors say.
Prosecutors said the immigration scam involved some of her husbands, who filed for permanent residence status shortly after the marriages.
Any divorces happened only after such filings were approved. It was unclear whether any of the men will be prosecuted.
The case was referred to the Bronx District Attorney\'s Office by Immigration and Customs Enforcement and the Department of Homeland Security\'s
Investigation Division. Seven of the men are from so-called "red-flagged" countries, including Egypt, Turkey, Georgia, Pakistan and Mali.
Her eighth husband, Rashid Rajput, was deported in 2006 to his native Pakistan after an investigation by the Joint Terrorism Task Force.
If convicted, Barrientos faces up to four years in prison.  Her next court appearance is scheduled for May 18.
"""
print(summarizer(ARTICLE, max_length=130, min_length=30, do_sample=False))

ZADANIE DOMOWE

  • sforkować repozytorium: https://git.wmi.amu.edu.pl/kubapok/paranormal-or-skeptic-ISI-public
  • finetunować klasyfikator bazujący na jakieś pretrenowanej sieć typu transformer (np BERT, Roberta). Można użyć dowolnej biblioteki (np hugging face, fairseq)
  • stworzyć predykcje w plikach dev-0/out.tsv oraz test-A/out.tsv
  • wynik accuracy sprawdzony za pomocą narzędzia geval (patrz poprzednie zadanie) powinien wynosić conajmniej 0.67
  • 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