ugb/3_RNN.ipynb

937 lines
274 KiB
Plaintext
Raw Normal View History

2024-05-10 14:56:49 +02:00
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Uczenie głębokie przetwarzanie tekstu laboratoria\n",
"# 3. RNN"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Podejście softmax z embeddingami na przykładzie NER"
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 42,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Defaulting to user installation because normal site-packages is not writeable\n",
"Requirement already satisfied: torch in /home/pawel/.local/lib/python3.10/site-packages (2.3.0)\n",
2024-05-13 10:07:22 +02:00
"Requirement already satisfied: torchtext in /home/pawel/.local/lib/python3.10/site-packages (0.18.0)\n",
2024-05-13 10:28:58 +02:00
"Requirement already satisfied: nvidia-cusolver-cu12==11.4.5.107 in /home/pawel/.local/lib/python3.10/site-packages (from torch) (11.4.5.107)\n",
"Requirement already satisfied: jinja2 in /home/pawel/.local/lib/python3.10/site-packages (from torch) (3.1.3)\n",
"Requirement already satisfied: typing-extensions>=4.8.0 in /home/pawel/.local/lib/python3.10/site-packages (from torch) (4.10.0)\n",
"Requirement already satisfied: nvidia-cuda-cupti-cu12==12.1.105 in /home/pawel/.local/lib/python3.10/site-packages (from torch) (12.1.105)\n",
2024-05-13 10:07:22 +02:00
"Requirement already satisfied: nvidia-nccl-cu12==2.20.5 in /home/pawel/.local/lib/python3.10/site-packages (from torch) (2.20.5)\n",
"Requirement already satisfied: nvidia-cuda-runtime-cu12==12.1.105 in /home/pawel/.local/lib/python3.10/site-packages (from torch) (12.1.105)\n",
2024-05-13 10:28:58 +02:00
"Requirement already satisfied: nvidia-nvtx-cu12==12.1.105 in /home/pawel/.local/lib/python3.10/site-packages (from torch) (12.1.105)\n",
2024-05-13 10:07:22 +02:00
"Requirement already satisfied: filelock in /home/pawel/.local/lib/python3.10/site-packages (from torch) (3.13.1)\n",
2024-05-13 10:28:58 +02:00
"Requirement already satisfied: sympy in /home/pawel/.local/lib/python3.10/site-packages (from torch) (1.12)\n",
"Requirement already satisfied: nvidia-cuda-nvrtc-cu12==12.1.105 in /home/pawel/.local/lib/python3.10/site-packages (from torch) (12.1.105)\n",
2024-05-13 10:07:22 +02:00
"Requirement already satisfied: triton==2.3.0 in /home/pawel/.local/lib/python3.10/site-packages (from torch) (2.3.0)\n",
2024-05-13 10:28:58 +02:00
"Requirement already satisfied: nvidia-cublas-cu12==12.1.3.1 in /home/pawel/.local/lib/python3.10/site-packages (from torch) (12.1.3.1)\n",
"Requirement already satisfied: nvidia-cudnn-cu12==8.9.2.26 in /home/pawel/.local/lib/python3.10/site-packages (from torch) (8.9.2.26)\n",
"Requirement already satisfied: nvidia-curand-cu12==10.3.2.106 in /home/pawel/.local/lib/python3.10/site-packages (from torch) (10.3.2.106)\n",
"Requirement already satisfied: nvidia-cufft-cu12==11.0.2.54 in /home/pawel/.local/lib/python3.10/site-packages (from torch) (11.0.2.54)\n",
2024-05-13 10:07:22 +02:00
"Requirement already satisfied: fsspec in /home/pawel/.local/lib/python3.10/site-packages (from torch) (2024.2.0)\n",
"Requirement already satisfied: nvidia-cusparse-cu12==12.1.0.106 in /home/pawel/.local/lib/python3.10/site-packages (from torch) (12.1.0.106)\n",
2024-05-10 14:56:49 +02:00
"Requirement already satisfied: networkx in /home/pawel/.local/lib/python3.10/site-packages (from torch) (3.3)\n",
"Requirement already satisfied: nvidia-nvjitlink-cu12 in /home/pawel/.local/lib/python3.10/site-packages (from nvidia-cusolver-cu12==11.4.5.107->torch) (12.4.127)\n",
"Requirement already satisfied: requests in /home/pawel/.local/lib/python3.10/site-packages (from torchtext) (2.31.0)\n",
"Requirement already satisfied: numpy in /home/pawel/.local/lib/python3.10/site-packages (from torchtext) (1.26.4)\n",
2024-05-13 10:28:58 +02:00
"Requirement already satisfied: tqdm in /home/pawel/.local/lib/python3.10/site-packages (from torchtext) (4.66.2)\n",
2024-05-10 14:56:49 +02:00
"Requirement already satisfied: MarkupSafe>=2.0 in /home/pawel/.local/lib/python3.10/site-packages (from jinja2->torch) (2.1.5)\n",
"Requirement already satisfied: urllib3<3,>=1.21.1 in /home/pawel/.local/lib/python3.10/site-packages (from requests->torchtext) (2.2.1)\n",
2024-05-13 10:07:22 +02:00
"Requirement already satisfied: charset-normalizer<4,>=2 in /home/pawel/.local/lib/python3.10/site-packages (from requests->torchtext) (3.3.2)\n",
2024-05-13 10:28:58 +02:00
"Requirement already satisfied: idna<4,>=2.5 in /home/pawel/.local/lib/python3.10/site-packages (from requests->torchtext) (3.6)\n",
"Requirement already satisfied: certifi>=2017.4.17 in /home/pawel/.local/lib/python3.10/site-packages (from requests->torchtext) (2024.2.2)\n",
2024-05-13 10:07:22 +02:00
"Requirement already satisfied: mpmath>=0.19 in /home/pawel/.local/lib/python3.10/site-packages (from sympy->torch) (1.3.0)\n"
2024-05-10 14:56:49 +02:00
]
}
],
"source": [
"!pip install torch torchtext"
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 43,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [],
"source": [
"from collections import Counter\n",
"\n",
"import torch\n",
"from datasets import load_dataset\n",
"from torchtext.vocab import vocab\n",
"from tqdm.notebook import tqdm"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Wczytujemy zbiór danych `conll2003` (https://huggingface.co/datasets/conll2003), który zawiera teksty oznaczone znacznikami części mowy (*POS tags*): "
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 44,
2024-05-10 14:56:49 +02:00
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"dataset = load_dataset(\"conll2003\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Poiżej funkcja, która tworzy słownik (https://pytorch.org/text/stable/vocab.html).\n",
"\n",
"Parametr `special` określa symbole specjalne:\n",
"* `<unk>` nieznany token\n",
"* `<pad>` wypełnienie\n",
"* `<bos>` początek zdania\n",
"* `<eos>` koniec zdania"
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 45,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [],
"source": [
"def build_vocab(dataset):\n",
" counter = Counter()\n",
" for document in dataset:\n",
" counter.update(document)\n",
2024-05-13 10:07:22 +02:00
" return vocab(counter, specials=[\"<unk>\", \"<pad>\", \"<bos>\", \"<eos>\"])"
2024-05-10 14:56:49 +02:00
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 46,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [],
"source": [
2024-05-13 10:07:22 +02:00
"v = build_vocab(dataset[\"train\"][\"tokens\"])"
2024-05-10 14:56:49 +02:00
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 47,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [],
"source": [
"itos = v.get_itos() # mapowanie indeksów na tokeny"
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 48,
2024-05-13 10:07:22 +02:00
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['<unk>', '<pad>', '<bos>', '<eos>', 'EU', 'rejects', 'German', 'call', 'to', 'boycott', 'British', 'lamb', '.', 'Peter', 'Blackburn', 'BRUSSELS', '1996-08-22', 'The', 'European', 'Commission', 'said', 'on', 'Thursday', 'it', 'disagreed', 'with', 'advice', 'consumers', 'shun', 'until', 'scientists', 'determine', 'whether', 'mad', 'cow', 'disease', 'can', 'be', 'transmitted', 'sheep', 'Germany', \"'s\", 'representative', 'the', 'Union', 'veterinary', 'committee', 'Werner', 'Zwingmann', 'Wednesday', 'should', 'buy', 'sheepmeat', 'from', 'countries', 'other', 'than', 'Britain', 'scientific', 'was', 'clearer', '\"', 'We', 'do', \"n't\", 'support', 'any', 'such', 'recommendation', 'because', 'we', 'see', 'grounds', 'for', ',', 'chief', 'spokesman', 'Nikolaus', 'van', 'der', 'Pas', 'told', 'a', 'news', 'briefing', 'He', 'further', 'study', 'required', 'and', 'if', 'found', 'that', 'action', 'needed', 'taken', 'by', 'proposal', 'last', 'month', 'Farm', 'Commissioner', 'Franz', 'Fischler', 'ban', 'brains', 'spleens', 'spinal', 'cords', 'human', 'animal', 'food', 'chains', 'highly', 'specific', 'precautionary', 'move', 'protect', 'health', 'proposed', 'EU-wide', 'measures', 'after', 'reports', 'France', 'under', 'laboratory', 'conditions', 'could', 'contract', 'Bovine', 'Spongiform', 'Encephalopathy', '(', 'BSE', ')', '--', 'But', 'agreed', 'review', 'his', 'standing', 'mational', 'officials', 'questioned', 'justified', 'as', 'there', 'only', 'slight', 'risk', 'Spanish', 'Minister', 'Loyola', 'de', 'Palacio', 'had', 'earlier', 'accused', 'at', 'an', 'farm', 'ministers', \"'\", 'meeting', 'of', 'causing', 'unjustified', 'alarm', 'through', 'dangerous', 'generalisation', 'Only', 'backed', 'multidisciplinary', 'committees', 'are', 'due', 're-examine', 'issue', 'early', 'next', 'make', 'recommendations', 'senior', 'Sheep', 'have', 'long', 'been', 'known', 'scrapie', 'brain-wasting', 'similar', 'which', 'is', 'believed', 'transferred', 'cattle', 'feed', 'containing', 'waste', 'farmers', 'denied', 'danger', 'their', 'but', 'expressed', 'concern', 'government', 'avoid', 'might', 'influence', 'across', 'Europe', 'What', 'extremely', 'careful', 'how', 'going', 'take', 'lead', 'Welsh', 'National', 'Farmers', 'NFU', 'chairman', 'John', 'Lloyd', 'Jones', 'BBC', 'radio', 'Bonn', 'has', 'led', 'efforts', 'public', 'consumer', 'confidence', 'collapsed', 'in', 'March', 'report', 'suggested', 'humans', 'illness', 'eating', 'contaminated', 'beef', 'imported', '47,600', 'year', 'nearly', 'half', 'total', 'imports', 'It', 'brought', '4,275', 'tonnes', 'mutton', 'some', '10', 'percent', 'overall', 'Rare', 'Hendrix', 'song', 'draft', 'sells', 'almost', '$', '17,000', 'LONDON', 'A', 'rare', 'handwritten', 'U.S.', 'guitar', 'legend', 'Jimi', 'sold', 'auction', 'late', 'musician', 'favourite', 'possessions', 'Florida', 'restaurant', 'paid', '10,925', 'pounds', '16,935', 'Ai', 'no', 'telling', 'penned', 'piece', 'London', 'hotel', 'stationery', '1966', 'At', 'end', 'January', '1967', 'concert', 'English', 'city', 'Nottingham', 'he', 'threw', 'sheet', 'paper', 'into', 'audience', 'where', 'retrieved', 'fan', 'Buyers', 'also', 'snapped', 'up', '16', 'items', 'were', 'put', 'former', 'girlfriend', 'Kathy', 'Etchingham', 'who', 'lived', 'him', '1969', 'They', 'included', 'black', 'lacquer', 'mother', 'pearl', 'inlaid', 'box', 'used', 'store', 'drugs', 'anonymous', 'Australian', 'purchaser', 'bought', '5,060', '7,845', 'guitarist', 'died', 'overdose', '1970', 'aged', '27', 'China', 'says', 'Taiwan', 'spoils', 'atmosphere', 'talks', 'BEIJING', 'Taipei', 'spoiling', 'resumption', 'Strait', 'visit', 'Ukraine', 'Taiwanese', 'Vice', 'President', 'Lien', 'Chan', 'this', 'week', 'infuriated', 'Beijing', 'Speaking', 'hours', 'Chinese', 'state', 'media', 'time', 'right', 'engage', 'political', 'Foreign', 'Ministry', 'Shen', 'Guofang', 'Reuters', ':', 'necessary', 'opening', 'disrupted', 'authorities', 'State', 'quoted', 'top', 'negotiator', 'Tang', 'Shubei', 'visiting', 'group', 'rivals', 'hold', 'Now', 'two', 'sides', '...', 'hostility', 'overseas', 'edition',
]
}
],
"source": [
"print(itos)"
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 49,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"23627"
]
},
2024-05-13 10:28:58 +02:00
"execution_count": 49,
2024-05-10 14:56:49 +02:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(itos) # liczba różnych tokenów w słowniku"
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 50,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
2024-05-13 10:07:22 +02:00
"5"
2024-05-10 14:56:49 +02:00
]
},
2024-05-13 10:28:58 +02:00
"execution_count": 50,
2024-05-10 14:56:49 +02:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
2024-05-13 10:07:22 +02:00
"v[\"rejects\"] # indeks tokenu `on`"
2024-05-10 14:56:49 +02:00
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 51,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0"
]
},
2024-05-13 10:28:58 +02:00
"execution_count": 51,
2024-05-10 14:56:49 +02:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"v[\"<unk>\"] # indeks nieznanego tokenu"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"W przypadku, gdy w analizowanym tekście znajdzie się token, którego nie ma w słowniku, będzie reprezentowany przez indeks domyślny (*default index*). Ustawiamy, żeby był taki sam, jak indeks „nieznanego tokenu”:"
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 52,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [],
"source": [
"v.set_default_index(v[\"<unk>\"])"
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 53,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [],
"source": [
"def data_process(dt):\n",
" # Wektoryzacja dokumentów tekstowych.\n",
2024-05-13 10:07:22 +02:00
" return [\n",
" torch.tensor(\n",
" [v[\"<bos>\"]] + [v[token] for token in document] + [v[\"<eos>\"]],\n",
" dtype=torch.long,\n",
" )\n",
" for document in dt\n",
" ]"
2024-05-10 14:56:49 +02:00
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 54,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [],
"source": [
"def labels_process(dt):\n",
2024-05-13 08:23:16 +02:00
" # Wektoryzacja etykiet (NER)\n",
2024-05-13 10:07:22 +02:00
" return [torch.tensor([0] + document + [0], dtype=torch.long) for document in dt]"
2024-05-10 14:56:49 +02:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Teraz wektoryzujemy wszystkie dane:"
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 55,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [],
"source": [
2024-05-13 10:07:22 +02:00
"train_tokens_ids = data_process(dataset[\"train\"][\"tokens\"])"
2024-05-10 14:56:49 +02:00
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 56,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [],
"source": [
2024-05-13 10:07:22 +02:00
"test_tokens_ids = data_process(dataset[\"test\"][\"tokens\"])"
2024-05-10 14:56:49 +02:00
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 57,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [],
"source": [
2024-05-13 10:07:22 +02:00
"validation_tokens_ids = data_process(dataset[\"validation\"][\"tokens\"])"
2024-05-10 14:56:49 +02:00
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 58,
2024-05-10 14:56:49 +02:00
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
2024-05-13 10:07:22 +02:00
"train_labels = labels_process(dataset[\"train\"][\"ner_tags\"])"
2024-05-10 14:56:49 +02:00
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 59,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [],
"source": [
2024-05-13 10:07:22 +02:00
"validation_labels = labels_process(dataset[\"validation\"][\"ner_tags\"])"
2024-05-10 14:56:49 +02:00
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 60,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [],
"source": [
2024-05-13 10:07:22 +02:00
"test_labels = labels_process(dataset[\"test\"][\"ner_tags\"])"
2024-05-10 14:56:49 +02:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Przykład, jak wyglądają dane po zwektoryzowaniu:"
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 61,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"tensor([ 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 3])"
]
},
2024-05-13 10:28:58 +02:00
"execution_count": 61,
2024-05-10 14:56:49 +02:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"train_tokens_ids[0]"
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 62,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'id': '0',\n",
" 'tokens': ['EU',\n",
" 'rejects',\n",
" 'German',\n",
" 'call',\n",
" 'to',\n",
" 'boycott',\n",
" 'British',\n",
" 'lamb',\n",
" '.'],\n",
" 'pos_tags': [22, 42, 16, 21, 35, 37, 16, 21, 7],\n",
" 'chunk_tags': [11, 21, 11, 12, 21, 22, 11, 12, 0],\n",
" 'ner_tags': [3, 0, 7, 0, 0, 0, 7, 0, 0]}"
]
},
2024-05-13 10:28:58 +02:00
"execution_count": 62,
2024-05-10 14:56:49 +02:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
2024-05-13 10:07:22 +02:00
"dataset[\"train\"][0]"
2024-05-10 14:56:49 +02:00
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 63,
2024-05-10 14:56:49 +02:00
"metadata": {
"scrolled": true
},
"outputs": [
{
"data": {
"text/plain": [
"tensor([0, 3, 0, 7, 0, 0, 0, 7, 0, 0, 0])"
]
},
2024-05-13 10:28:58 +02:00
"execution_count": 63,
2024-05-10 14:56:49 +02:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"train_labels[0]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Funkcja, której użyjemy do ewaluacji:"
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 64,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [],
"source": [
"def get_scores(y_true, y_pred):\n",
" # Funkcja zwraca precyzję, pokrycie i F1\n",
" acc_score = 0\n",
" tp = 0\n",
" fp = 0\n",
" selected_items = 0\n",
2024-05-13 10:07:22 +02:00
" relevant_items = 0\n",
2024-05-10 14:56:49 +02:00
"\n",
2024-05-13 10:07:22 +02:00
" for p, t in zip(y_pred, y_true):\n",
2024-05-10 14:56:49 +02:00
" if p == t:\n",
2024-05-13 10:07:22 +02:00
" acc_score += 1\n",
2024-05-10 14:56:49 +02:00
"\n",
" if p > 0 and p == t:\n",
2024-05-13 10:07:22 +02:00
" tp += 1\n",
2024-05-10 14:56:49 +02:00
"\n",
" if p > 0:\n",
" selected_items += 1\n",
"\n",
2024-05-13 10:07:22 +02:00
" if t > 0:\n",
" relevant_items += 1\n",
2024-05-10 14:56:49 +02:00
"\n",
" if selected_items == 0:\n",
" precision = 1.0\n",
" else:\n",
" precision = tp / selected_items\n",
2024-05-13 10:07:22 +02:00
"\n",
2024-05-10 14:56:49 +02:00
" if relevant_items == 0:\n",
" recall = 1.0\n",
" else:\n",
" recall = tp / relevant_items\n",
2024-05-13 10:07:22 +02:00
"\n",
" if precision + recall == 0.0:\n",
2024-05-10 14:56:49 +02:00
" f1 = 0.0\n",
" else:\n",
2024-05-13 10:07:22 +02:00
" f1 = 2 * precision * recall / (precision + recall)\n",
2024-05-10 14:56:49 +02:00
"\n",
" return precision, recall, f1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2024-05-13 08:23:16 +02:00
"Ile mamy różnych tagów NER?"
2024-05-10 14:56:49 +02:00
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 65,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"9\n"
]
}
],
"source": [
2024-05-13 10:07:22 +02:00
"num_tags = max([max(x) for x in dataset[\"train\"][\"ner_tags\"]]) + 1\n",
2024-05-10 14:56:49 +02:00
"print(num_tags)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Implementacja rekurencyjnej sieci neuronowej LSTM:"
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 66,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [],
"source": [
"class LSTM(torch.nn.Module):\n",
"\n",
" def __init__(self):\n",
" super(LSTM, self).__init__()\n",
2024-05-13 10:07:22 +02:00
" self.emb = torch.nn.Embedding(len(v.get_itos()), 100)\n",
" self.rec = torch.nn.LSTM(100, 256, 1, batch_first=True)\n",
" self.fc1 = torch.nn.Linear(256, num_tags)\n",
2024-05-10 14:56:49 +02:00
"\n",
" def forward(self, x):\n",
" emb = torch.relu(self.emb(x))\n",
" lstm_output, (h_n, c_n) = self.rec(emb)\n",
" out_weights = self.fc1(lstm_output)\n",
" return out_weights"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Stworzenie modelu:"
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 67,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [],
"source": [
"lstm = LSTM()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Definicja funkcji kosztu:"
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 68,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [],
"source": [
"criterion = torch.nn.CrossEntropyLoss()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Definicja optymalizatora:"
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 69,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [],
"source": [
"optimizer = torch.optim.Adam(lstm.parameters())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Funkcja do ewaluacji modelu:"
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 70,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [],
"source": [
"def eval_model(dataset_tokens, dataset_labels, model):\n",
" Y_true = []\n",
" Y_pred = []\n",
" for i in tqdm(range(len(dataset_labels))):\n",
" batch_tokens = dataset_tokens[i].unsqueeze(0)\n",
" tags = list(dataset_labels[i].numpy())\n",
" Y_true += tags\n",
2024-05-13 10:07:22 +02:00
"\n",
2024-05-10 14:56:49 +02:00
" Y_batch_pred_weights = model(batch_tokens).squeeze(0)\n",
2024-05-13 10:07:22 +02:00
" Y_batch_pred = torch.argmax(Y_batch_pred_weights, 1)\n",
2024-05-10 14:56:49 +02:00
" Y_pred += list(Y_batch_pred.numpy())\n",
"\n",
2024-05-13 10:07:22 +02:00
" return get_scores(Y_true, Y_pred)"
2024-05-10 14:56:49 +02:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Uczenie modelu:"
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 71,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [],
"source": [
"NUM_EPOCHS = 5"
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 72,
2024-05-10 14:56:49 +02:00
"metadata": {
"scrolled": false
},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
2024-05-13 10:28:58 +02:00
"model_id": "2f51ce06b51e454987745fdce27fcdca",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/14041 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "c47750eda30c48a7849a31dadd912572",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/3250 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"(0.4973622179818161, 0.515052888527258, 0.5060529922338968)\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "bbd0eb51c6a5455ca90a04a8f0c48c52",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/14041 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "ead8b2d7b3e343f6813a67360c04c3a1",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/3250 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"(0.6815704731236066, 0.6396605835173776, 0.6599508304850992)\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "5c5c23b35aec44538e3c555942d03c83",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/14041 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "e3760b37c7254fabbe3af2efa6f64fc2",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/3250 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"(0.7551872469635628, 0.693827734511217, 0.7232083358575151)\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "be4746c7c6344842bba71fd9b0b68c2d",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/14041 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "1f6377f9948248f8902fbca64aa2c97c",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/3250 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"(0.7720238820519069, 0.7364872718819017, 0.753837001784652)\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "48f6598908994c04b3d5d95218ec1769",
2024-05-10 14:56:49 +02:00
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/14041 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
2024-05-13 10:28:58 +02:00
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "fb0f01827bbe4db7a23e4fd8a30ca467",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/3250 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"(0.8183865412637435, 0.7181215854934325, 0.7649826646854879)\n"
2024-05-10 14:56:49 +02:00
]
}
],
"source": [
"for i in range(NUM_EPOCHS):\n",
" lstm.train()\n",
2024-05-13 10:07:22 +02:00
" # for i in tqdm(range(500)):\n",
2024-05-10 14:56:49 +02:00
" for i in tqdm(range(len(train_labels))):\n",
" batch_tokens = train_tokens_ids[i].unsqueeze(0)\n",
" tags = train_labels[i].unsqueeze(1)\n",
2024-05-13 10:07:22 +02:00
"\n",
2024-05-10 14:56:49 +02:00
" predicted_tags = lstm(batch_tokens)\n",
"\n",
" optimizer.zero_grad()\n",
2024-05-13 10:07:22 +02:00
" loss = criterion(predicted_tags.squeeze(0), tags.squeeze(1))\n",
"\n",
2024-05-10 14:56:49 +02:00
" loss.backward()\n",
" optimizer.step()\n",
2024-05-13 10:07:22 +02:00
"\n",
2024-05-10 14:56:49 +02:00
" lstm.eval()\n",
" print(eval_model(validation_tokens_ids, validation_labels, lstm))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Ewaluacja:"
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 73,
2024-05-10 14:56:49 +02:00
"metadata": {
"scrolled": true
},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
2024-05-13 10:28:58 +02:00
"model_id": "a6d17919f9194594864a4e0b1fc1d497",
2024-05-10 14:56:49 +02:00
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/3250 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": [
2024-05-13 10:28:58 +02:00
"(0.8183865412637435, 0.7181215854934325, 0.7649826646854879)"
2024-05-10 14:56:49 +02:00
]
},
2024-05-13 10:28:58 +02:00
"execution_count": 73,
2024-05-10 14:56:49 +02:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"eval_model(validation_tokens_ids, validation_labels, lstm)"
]
},
{
"cell_type": "code",
2024-05-13 10:28:58 +02:00
"execution_count": 74,
2024-05-10 14:56:49 +02:00
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
2024-05-13 10:28:58 +02:00
"model_id": "a0d8b8bf66094bc1b527e578aa8de2a3",
2024-05-10 14:56:49 +02:00
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/3453 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": [
2024-05-13 10:28:58 +02:00
"(0.7458321146534074, 0.628698224852071, 0.6822742474916388)"
2024-05-10 14:56:49 +02:00
]
},
2024-05-13 10:28:58 +02:00
"execution_count": 74,
2024-05-10 14:56:49 +02:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"eval_model(test_tokens_ids, test_labels, lstm)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Zadanie 3\n",
"\n",
"Sklonuj repozytorium https://git.wmi.amu.edu.pl/kubapok/en-ner-conll-2003\n",
"\n",
2024-05-13 10:07:22 +02:00
"Stwórz model *sequence labelling* realizujący zadanie NER, oparty o dowolną rekurencyjną sieć neuronową (możesz wzorować się na przykładzie z zajęć).\n",
2024-05-10 14:56:49 +02:00
"\n",
"W plikach dev-0/out.tsv oraz test-A/out.tsv umieść wyniki predykcji dla dev-0/in.tsv i test-A/in.tsv odpowiednio.\n",
"Do ewaluacji wykorzystaj narzędzie GEval (https://gitlab.com/filipg/geval):\n",
"\n",
" wget https://gonito.net/get/bin/geval\n",
" chmod u+x geval\n",
" ./geval --help\n",
"\n",
"Liczba punktów uzyskanych za zadanie zależy od uzyskanej wartości accuracy na zbiorze `test-A` (wynik zaokrąglony w górę):\n",
"\n",
" points = math.ceil(accuracy * 7.0)\n",
"\n",
"⚠️ W systemie Moodle proszę załączyć plik `test-A/out.tsv` oraz link do repozytorium z rozwiązaniem zadania.\n",
" "
]
}
],
"metadata": {
"author": "Jakub Pokrywka",
"email": "kubapok@wmi.amu.edu.pl",
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"lang": "pl",
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.12"
},
"subtitle": "11.NER RNN[ćwiczenia]",
"title": "Ekstrakcja informacji",
"year": "2021"
},
"nbformat": 4,
"nbformat_minor": 4
}