thesis-prediction-ml/LanguageTranslation_Seq2Seq_GermanToEnglish.ipynb
2023-04-12 15:14:16 +02:00

493 lines
18 KiB
Text

{
"cells": [
{
"cell_type": "code",
"execution_count": 32,
"id": "c916a945",
"metadata": {},
"outputs": [],
"source": [
"from io import open\n",
"import unicodedata\n",
"import string\n",
"import re\n",
"import random\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import matplotlib.ticker as ticker\n",
"\n",
"import torch\n",
"import torch.nn as nn\n",
"from torch import optim\n",
"import torch.nn.functional as F"
]
},
{
"cell_type": "code",
"execution_count": 33,
"id": "84d8f145",
"metadata": {},
"outputs": [],
"source": [
"SOS_token =0\n",
"EOS_token=1"
]
},
{
"cell_type": "code",
"execution_count": 34,
"id": "903fb338",
"metadata": {},
"outputs": [],
"source": [
"class Lang:\n",
" def __init__(self,name):\n",
" self.name=name\n",
" self.word2index={}\n",
" self.word2count={}\n",
" self.index2word={0:'SOS',1:\"EOS\"}\n",
" self.n_words=2\n",
" \n",
" def addSentence(self,sentence):\n",
" for word in sentence.split(' '):\n",
" self.addWord(word)\n",
" \n",
" def addWord(self,word):\n",
" if word not in self.word2index:\n",
" self.word2index[word]=self.n_words\n",
" self.word2count[word]=1\n",
" self.index2word[self.n_words]=word\n",
" self.n_words +=1\n",
" else:\n",
" self.word2count[word] +=1\n",
" "
]
},
{
"cell_type": "code",
"execution_count": 35,
"id": "a9fee1c9",
"metadata": {},
"outputs": [],
"source": [
"def normalizeString(s):\n",
" s=s.lower().strip()\n",
" \n",
" s=''.join(\n",
" char for char in unicodedata.normalize('NFD',s)\n",
" if unicodedata.category(char) != 'Mn')\n",
" \n",
" s= re.sub(r\"([.!?])\",r\"\",s)\n",
" s= re.sub(r\"[^a-zA-Z.!?]+\",r\" \",s)\n",
" \n",
" return s"
]
},
{
"cell_type": "code",
"execution_count": 36,
"id": "7bb97104",
"metadata": {},
"outputs": [],
"source": [
"def readLangs(lang1,lang2,reverse=False):\n",
" print (\"reading\")\n",
" lines = open('datasets/data/%s-%s.txt'% (lang1,lang2),encoding=\"utf-8\"). \\\n",
" read().strip().split('\\n')\n",
"\n",
" pairs =[[normalizeString(s) for s in l.split('\\t')] for l in lines]\n",
"\n",
" if reverse:\n",
" pairs = [list(reversed(p)) for p in pairs]\n",
" input_lang=Lang(lang2)\n",
" output_lang=Lang(lang1)\n",
" else:\n",
" input_lang=Lang(lang1)\n",
" output_lang=Lang(lang2)\n",
"\n",
" return input_lang, output_lang, pairs\n"
]
},
{
"cell_type": "code",
"execution_count": 37,
"id": "3278e7c0",
"metadata": {},
"outputs": [],
"source": [
"MAX_LENGTH = 10"
]
},
{
"cell_type": "code",
"execution_count": 38,
"id": "8437d53d",
"metadata": {},
"outputs": [],
"source": [
"eng_prefixes=(\"ich habe\")"
]
},
{
"cell_type": "code",
"execution_count": 39,
"id": "d9a29144",
"metadata": {},
"outputs": [],
"source": [
"def filterPairs(pairs):\n",
" return [p for p in pairs\n",
" if\n",
" p[1].startswith(eng_prefixes)]"
]
},
{
"cell_type": "code",
"execution_count": 40,
"id": "c7d06079",
"metadata": {},
"outputs": [],
"source": [
"def prepareData(lang1, lang2, reverse=False):\n",
" input_lang,output_lang, pairs = readLangs(lang1,lang2,reverse)\n",
" print(\"Read %s sentence pairs\" % len(pairs))\n",
"\n",
" pairs = filterPairs(pairs)\n",
" print (\"Trimmed to %s sentence pair\" % len(pairs))\n",
"\n",
" for pair in pairs:\n",
" input_lang.addSentence(pair[0])\n",
" output_lang.addSentence(pair[1])\n",
" \n",
" print(\"Counted words:\")\n",
" print(input_lang.name,input_lang.n_words)\n",
" print(output_lang.name,output_lang.n_words)\n",
"\n",
" return input_lang, output_lang, pairs"
]
},
{
"cell_type": "code",
"execution_count": 41,
"id": "e5fa439b",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"reading\n",
"Read 261499 sentence pairs\n",
"Trimmed to 9195 sentence pair\n",
"Counted words:\n",
"deu 581\n",
"eng 4502\n",
"['cc by france attribution tatoebaorg zifre raggione ', 'ich habe mir die haare nicht gewaschen', 'i haven t washed my hair']\n"
]
}
],
"source": [
"input_lang,output_lang,pairs= prepareData('eng','deu',reverse=True)\n",
"print(random.choice(pairs))"
]
},
{
"cell_type": "code",
"execution_count": 42,
"id": "ff2860d3",
"metadata": {},
"outputs": [],
"source": [
"class EncoderRNN(nn.Module):\n",
" def __init__(self, input_size, hidden_size) :\n",
" super(EncoderRNN,self).__init__()\n",
"\n",
" self.hidden_size=hidden_size\n",
" self.embedding=nn.Embedding(input_size,hidden_size)\n",
" self.gru=nn.GRU(hidden_size,hidden_size)\n",
" \n",
" def forward(self,input,hidden):\n",
"\n",
" embedded=self.embedding(input).view(1,1,-1)\n",
" output=embedded\n",
" output,hidden= self.gru(output,hidden)\n",
"\n",
" return output,hidden\n",
" \n",
" def initHidden(self):\n",
" return torch.zeros(1,1,self.hidden_size)"
]
},
{
"cell_type": "code",
"execution_count": 43,
"id": "23ffacf6",
"metadata": {},
"outputs": [],
"source": [
"class DecoderRNN(nn.Module):\n",
"\n",
" def __init__(self, hidden_size, output_size):\n",
" super(DecoderRNN,self).__init__()\n",
"\n",
" self.hidden_size=hidden_size\n",
" self.embedding=nn.Embedding(output_size,hidden_size)\n",
" self.gru=nn.GRU(hidden_size,hidden_size)\n",
" self.out=nn.Linear(hidden_size,output_size)\n",
" self.softmax= nn.LogSoftmax(dim=1)\n",
"\n",
" def forward(self,input,hidden):\n",
"\n",
" output=self.embedding(input).view(1,1,-1)\n",
" output = F.relu(output)\n",
"\n",
" output , hidden = self.gru(output,hidden)\n",
"\n",
" output = self.softmax(self.out(output[0]))\n",
"\n",
" return output, hidden\n",
"\n",
" def initHidden(self):\n",
" return torch.zeros(1,1, self.hidden_size)"
]
},
{
"cell_type": "code",
"execution_count": 44,
"id": "5881c7a2",
"metadata": {},
"outputs": [],
"source": [
"def tensorFromSentence(lang,sentence):\n",
" indexes =[lang.word2index[word] for word in sentence.split(' ')]\n",
" indexes.append(EOS_token)\n",
"\n",
" return torch.tensor(indexes,dtype=torch.long).view(-1,1)"
]
},
{
"cell_type": "code",
"execution_count": 45,
"id": "05b1cdc3",
"metadata": {},
"outputs": [],
"source": [
"def tensorsFromPair(pair):\n",
" input_tensor = tensorFromSentence(input_lang,pair[0])\n",
" target_tensor = tensorFromSentence(output_lang,pair[1])\n",
"\n",
" return (input_tensor,target_tensor)"
]
},
{
"cell_type": "code",
"execution_count": 46,
"id": "2458ab76",
"metadata": {},
"outputs": [],
"source": [
"teacher_forcing_ratio = 0.5"
]
},
{
"cell_type": "code",
"execution_count": 30,
"id": "d504960d",
"metadata": {},
"outputs": [],
"source": [
"def train(input_tensor,target_tensor,encoder,decoder,encoder_optimizer,decoder_optimizer,criterion):\n",
"\n",
" encoder_hidden= encoder.initHidden()\n",
"\n",
" encoder_optimizer.zero_grad()\n",
" decoder_optimizer.zero_grad()\n",
"\n",
" input_length=input_tensor.size(0)\n",
" target_length = target_tensor.size(0)\n",
"\n",
" loss=0\n",
"\n",
" for ei in range(input_length):\n",
" encoder_output, encoder_hidden = encoder (input_tensor[ei],encoder_hidden)\n",
"\n",
" decoder_input = torch.tensor([[SOS_token]])\n",
"\n",
" decoder_hidden = encoder_hidden\n",
"\n",
" use_teacher_forcing = True if random.random()< teacher_forcing_ratio else False\n",
"\n",
" if use_teacher_forcing:\n",
"\n",
" for di in range(target_length):\n",
" decoder_output, decoder_hidden = decoder(decoder_input,decoder_hidden)\n",
"\n",
" \n",
"\n",
" loss += criterion(decoder_output,target_tensor[di])\n",
" \n",
" decoder_input = target_tensor[di]\n",
" else :\n",
"\n",
" for di in range(target_length):\n",
" decoder_output, decoder_hidden = decoder(decoder_input,decoder_hidden)\n",
"\n",
" topv, topi = decoder_output.topk(1)\n",
" decoder_input = topi.squeeze().detach()\n",
"\n",
" loss += criterion(decoder_output,target_tensor[di])\n",
"\n",
" if decoder_input.item()== EOS_token:\n",
" break\n",
" loss.backward()\n",
"\n",
" encoder_optimizer.step()\n",
" decoder_optimizer.step()\n",
"\n",
" return loss.item() / target_length\n",
"\n",
"\n",
"\n",
" \n"
]
},
{
"cell_type": "code",
"execution_count": 22,
"id": "0e31befa",
"metadata": {},
"outputs": [],
"source": [
"plot_losses =[]\n",
"print_loss_total =0\n",
"plot_loss_total =0"
]
},
{
"cell_type": "code",
"execution_count": 23,
"id": "d17a1e56",
"metadata": {},
"outputs": [],
"source": [
"hidden_size =256"
]
},
{
"cell_type": "code",
"execution_count": 27,
"id": "665b367d",
"metadata": {},
"outputs": [],
"source": [
"encoder1 = EncoderRNN(input_lang.n_words,hidden_size)\n",
"decoder1= DecoderRNN(hidden_size,output_lang.n_words)"
]
},
{
"cell_type": "code",
"execution_count": 28,
"id": "614615cb",
"metadata": {},
"outputs": [],
"source": [
"encoder_optimizer = optim.SGD(encoder1.parameters(), lr=0.01)\n",
"decoder_optimizer = optim.SGD(decoder1.parameters(), lr=0.01)\n",
"\n",
"training_pairs =[tensorsFromPair(random.choice(pairs))\n",
" for i in range(3000)]\n",
"\n",
"criterion = nn.NLLLoss()\n"
]
},
{
"cell_type": "code",
"execution_count": 31,
"id": "d7c931c8",
"metadata": {},
"outputs": [
{
"ename": "ValueError",
"evalue": "Expected input batch_size (1) to match target batch_size (0).",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[31], line 7\u001b[0m\n\u001b[1;32m 4\u001b[0m input_tensor \u001b[39m=\u001b[39m training_pairs[\u001b[39m0\u001b[39m]\n\u001b[1;32m 5\u001b[0m target_tensor \u001b[39m=\u001b[39m training_pairs[\u001b[39m1\u001b[39m]\n\u001b[0;32m----> 7\u001b[0m loss \u001b[39m=\u001b[39m train (input_tensor,target_tensor,\n\u001b[1;32m 8\u001b[0m encoder1,decoder1,\n\u001b[1;32m 9\u001b[0m encoder_optimizer,decoder_optimizer,\n\u001b[1;32m 10\u001b[0m criterion)\n\u001b[1;32m 12\u001b[0m print_loss_total\u001b[39m+\u001b[39m\u001b[39m=\u001b[39mloss\n\u001b[1;32m 14\u001b[0m plot_loss_total\u001b[39m+\u001b[39m\u001b[39m=\u001b[39mloss\n",
"Cell \u001b[0;32mIn[30], line 40\u001b[0m, in \u001b[0;36mtrain\u001b[0;34m(input_tensor, target_tensor, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion)\u001b[0m\n\u001b[1;32m 37\u001b[0m topv, topi \u001b[39m=\u001b[39m decoder_output\u001b[39m.\u001b[39mtopk(\u001b[39m1\u001b[39m)\n\u001b[1;32m 38\u001b[0m decoder_input \u001b[39m=\u001b[39m topi\u001b[39m.\u001b[39msqueeze()\u001b[39m.\u001b[39mdetach()\n\u001b[0;32m---> 40\u001b[0m loss \u001b[39m+\u001b[39m\u001b[39m=\u001b[39m criterion(decoder_output,target_tensor[di])\n\u001b[1;32m 42\u001b[0m \u001b[39mif\u001b[39;00m decoder_input\u001b[39m.\u001b[39mitem()\u001b[39m==\u001b[39m EOS_token:\n\u001b[1;32m 43\u001b[0m \u001b[39mbreak\u001b[39;00m\n",
"File \u001b[0;32m~/devnlp/.venv/lib/python3.9/site-packages/torch/nn/modules/module.py:1501\u001b[0m, in \u001b[0;36mModule._call_impl\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m 1496\u001b[0m \u001b[39m# If we don't have any hooks, we want to skip the rest of the logic in\u001b[39;00m\n\u001b[1;32m 1497\u001b[0m \u001b[39m# this function, and just call forward.\u001b[39;00m\n\u001b[1;32m 1498\u001b[0m \u001b[39mif\u001b[39;00m \u001b[39mnot\u001b[39;00m (\u001b[39mself\u001b[39m\u001b[39m.\u001b[39m_backward_hooks \u001b[39mor\u001b[39;00m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39m_backward_pre_hooks \u001b[39mor\u001b[39;00m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39m_forward_hooks \u001b[39mor\u001b[39;00m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39m_forward_pre_hooks\n\u001b[1;32m 1499\u001b[0m \u001b[39mor\u001b[39;00m _global_backward_pre_hooks \u001b[39mor\u001b[39;00m _global_backward_hooks\n\u001b[1;32m 1500\u001b[0m \u001b[39mor\u001b[39;00m _global_forward_hooks \u001b[39mor\u001b[39;00m _global_forward_pre_hooks):\n\u001b[0;32m-> 1501\u001b[0m \u001b[39mreturn\u001b[39;00m forward_call(\u001b[39m*\u001b[39;49margs, \u001b[39m*\u001b[39;49m\u001b[39m*\u001b[39;49mkwargs)\n\u001b[1;32m 1502\u001b[0m \u001b[39m# Do not call functions when jit is used\u001b[39;00m\n\u001b[1;32m 1503\u001b[0m full_backward_hooks, non_full_backward_hooks \u001b[39m=\u001b[39m [], []\n",
"File \u001b[0;32m~/devnlp/.venv/lib/python3.9/site-packages/torch/nn/modules/loss.py:216\u001b[0m, in \u001b[0;36mNLLLoss.forward\u001b[0;34m(self, input, target)\u001b[0m\n\u001b[1;32m 215\u001b[0m \u001b[39mdef\u001b[39;00m \u001b[39mforward\u001b[39m(\u001b[39mself\u001b[39m, \u001b[39minput\u001b[39m: Tensor, target: Tensor) \u001b[39m-\u001b[39m\u001b[39m>\u001b[39m Tensor:\n\u001b[0;32m--> 216\u001b[0m \u001b[39mreturn\u001b[39;00m F\u001b[39m.\u001b[39;49mnll_loss(\u001b[39minput\u001b[39;49m, target, weight\u001b[39m=\u001b[39;49m\u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mweight, ignore_index\u001b[39m=\u001b[39;49m\u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mignore_index, reduction\u001b[39m=\u001b[39;49m\u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mreduction)\n",
"File \u001b[0;32m~/devnlp/.venv/lib/python3.9/site-packages/torch/nn/functional.py:2704\u001b[0m, in \u001b[0;36mnll_loss\u001b[0;34m(input, target, weight, size_average, ignore_index, reduce, reduction)\u001b[0m\n\u001b[1;32m 2702\u001b[0m \u001b[39mif\u001b[39;00m size_average \u001b[39mis\u001b[39;00m \u001b[39mnot\u001b[39;00m \u001b[39mNone\u001b[39;00m \u001b[39mor\u001b[39;00m reduce \u001b[39mis\u001b[39;00m \u001b[39mnot\u001b[39;00m \u001b[39mNone\u001b[39;00m:\n\u001b[1;32m 2703\u001b[0m reduction \u001b[39m=\u001b[39m _Reduction\u001b[39m.\u001b[39mlegacy_get_string(size_average, reduce)\n\u001b[0;32m-> 2704\u001b[0m \u001b[39mreturn\u001b[39;00m torch\u001b[39m.\u001b[39;49m_C\u001b[39m.\u001b[39;49m_nn\u001b[39m.\u001b[39;49mnll_loss_nd(\u001b[39minput\u001b[39;49m, target, weight, _Reduction\u001b[39m.\u001b[39;49mget_enum(reduction), ignore_index)\n",
"\u001b[0;31mValueError\u001b[0m: Expected input batch_size (1) to match target batch_size (0)."
]
}
],
"source": [
"for iter in range(1,3001):\n",
"\n",
" training_pairs = training_pairs[iter-1]\n",
" input_tensor = training_pairs[0]\n",
" target_tensor = training_pairs[1]\n",
"\n",
" loss = train (input_tensor,target_tensor,\n",
" encoder1,decoder1,\n",
" encoder_optimizer,decoder_optimizer,\n",
" criterion)\n",
" \n",
" print_loss_total+=loss\n",
"\n",
" plot_loss_total+=loss\n",
"\n",
" if iter % 1000 ==0:\n",
" print_loss_avg = print_loss_total /100\n",
" print_loss_total =0\n",
"\n",
" print ('iteration -%d loss - %.4f' % (iter,print_loss_avg))\n",
" \n",
" if iter % 100 ==0:\n",
" print_loss_avg =plot_loss_total /100\n",
"\n",
" plot_losses.append(print_loss_avg)\n",
" plot_loss_total=0\n",
"\n",
"fig,ax = plt.subplots(figsize=(15,8))\n",
"\n",
"loc = ticker.MultipleLocator(base=0.2)\n",
"\n",
"ax.yaxis.set_major_locator(loc)\n",
"\n",
"plt.plot(plot_losses)\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8e2a300e",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"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.9.7"
}
},
"nbformat": 4,
"nbformat_minor": 5
}