├── .gitignore
├── HMM.ipynb
├── LICENSE
├── README.md
├── data.py
├── data
└── train
│ └── training.txt
├── helper_functions.py
├── img
├── hmm.png
└── selfies.png
├── main.py
├── models.py
└── training.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | *.egg-info/
24 | .installed.cfg
25 | *.egg
26 | MANIFEST
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | nosetests.xml
45 | coverage.xml
46 | *.cover
47 | .hypothesis/
48 | .pytest_cache/
49 |
50 | # Translations
51 | *.mo
52 | *.pot
53 |
54 | # Django stuff:
55 | *.log
56 | local_settings.py
57 | db.sqlite3
58 |
59 | # Flask stuff:
60 | instance/
61 | .webassets-cache
62 |
63 | # Scrapy stuff:
64 | .scrapy
65 |
66 | # Sphinx documentation
67 | docs/_build/
68 |
69 | # PyBuilder
70 | target/
71 |
72 | # Jupyter Notebook
73 | .ipynb_checkpoints
74 |
75 | # pyenv
76 | .python-version
77 |
78 | # celery beat schedule file
79 | celerybeat-schedule
80 |
81 | # SageMath parsed files
82 | *.sage.py
83 |
84 | # Environments
85 | .env
86 | .venv
87 | env/
88 | venv/
89 | ENV/
90 | env.bak/
91 | venv.bak/
92 |
93 | # Spyder project settings
94 | .spyderproject
95 | .spyproject
96 |
97 | # Rope project settings
98 | .ropeproject
99 |
100 | # mkdocs documentation
101 | /site
102 |
103 | # mypy
104 | .mypy_cache/
105 |
--------------------------------------------------------------------------------
/HMM.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "nbformat": 4,
3 | "nbformat_minor": 0,
4 | "metadata": {
5 | "colab": {
6 | "name": "HMM.ipynb",
7 | "provenance": [],
8 | "collapsed_sections": [
9 | "Z3zUUYH0giKV",
10 | "qBCrFobsEM8X"
11 | ]
12 | },
13 | "kernelspec": {
14 | "name": "python3",
15 | "display_name": "Python 3"
16 | },
17 | "accelerator": "GPU"
18 | },
19 | "cells": [
20 | {
21 | "cell_type": "markdown",
22 | "metadata": {
23 | "id": "lDJIV2EVBuFZ"
24 | },
25 | "source": [
26 | "# Fun with Hidden Markov Models\n",
27 | "*by Loren Lugosch*"
28 | ]
29 | },
30 | {
31 | "cell_type": "markdown",
32 | "metadata": {
33 | "id": "_rWFkdjYOlk8"
34 | },
35 | "source": [
36 | "This notebook introduces the Hidden Markov Model (HMM), a simple model for sequential data.\n",
37 | "\n",
38 | "We will see:\n",
39 | "- what an HMM is and when you might want to use it;\n",
40 | "- the so-called \"three problems\" of an HMM; and \n",
41 | "- how to implement an HMM in PyTorch.\n",
42 | "\n",
43 | "(The code in this notebook can also be found at https://github.com/lorenlugosch/pytorch_HMM.)"
44 | ]
45 | },
46 | {
47 | "cell_type": "markdown",
48 | "metadata": {
49 | "id": "efPPcGy0gP6H"
50 | },
51 | "source": [
52 | "A hypothetical scenario\n",
53 | "------\n",
54 | "\n",
55 | "To motivate the use of HMMs, imagine that you have a friend who gets to do a lot of travelling. Every day, this jet-setting friend sends you a selfie from the city they’re in, to make you envious."
56 | ]
57 | },
58 | {
59 | "cell_type": "markdown",
60 | "metadata": {
61 | "id": "Cs3z7pnVib9g"
62 | },
63 | "source": [
64 | "
\n",
65 | "\n",
66 | "\n",
67 | "\n",
68 | "\n",
69 | "\n",
70 | "\n"
71 | ]
72 | },
73 | {
74 | "cell_type": "markdown",
75 | "metadata": {
76 | "id": "hTPNK3IjirDA"
77 | },
78 | "source": [
79 | "How would you go about guessing which city the friend is in each day, just by looking at the selfies?\n",
80 | "\n",
81 | "If the selfie contains a really obvious landmark, like the Eiffel Tower, it will be easy to figure out where the photo was taken. If not, it will be a lot harder to infer the city.\n",
82 | "\n",
83 | "But we have a clue to help us: the city the friend is in each day is not totally random. For example, the friend will probably remain in the same city for a few days to sightsee before flying to a new city."
84 | ]
85 | },
86 | {
87 | "cell_type": "markdown",
88 | "metadata": {
89 | "id": "k4g7IG7CBx-Y"
90 | },
91 | "source": [
92 | "## The HMM setup\n",
93 | "\n",
94 | "The hypothetical scenario of the friend travelling between cities and sending you selfies can be modeled using an HMM.\n"
95 | ]
96 | },
97 | {
98 | "cell_type": "markdown",
99 | "metadata": {
100 | "id": "NpwgbDTnRzRa"
101 | },
102 | "source": [
103 | "An HMM models a system that is in a particular state at any given time and produces an output that depends on that state. \n",
104 | "\n",
105 | "At each timestep or clock tick, the system randomly decides on a new state and jumps into that state. The system then randomly generates an observation. The states are \"hidden\": we can't observe them. (In the cities/selfies analogy, the unknown cities would be the hidden states, and the selfies would be the observations.)\n",
106 | "\n",
107 | "Let's denote the sequence of states as $\\mathbf{z} = \\{z_1, z_2, \\dots, z_T \\}$, where each state is one of a finite set of $N$ states, and the sequence of observations as $\\mathbf{x} = \\{x_1, x_2, \\dots, x_T\\}$. The observations could be discrete, like letters, or real-valued, like audio frames."
108 | ]
109 | },
110 | {
111 | "cell_type": "markdown",
112 | "metadata": {
113 | "id": "uV5fAhEQDAcJ"
114 | },
115 | "source": [
116 | "\n",
117 | "\n",
118 | "\n",
119 | ""
120 | ]
121 | },
122 | {
123 | "cell_type": "markdown",
124 | "metadata": {
125 | "id": "vMPrA6Uv-u-K"
126 | },
127 | "source": [
128 | "An HMM makes two key assumptions:\n",
129 | "- **Assumption 1:** The state at time $t$ depends *only* on the state at the previous time $t-1$. \n",
130 | "- **Assumption 2:** The output at time $t$ depends *only* on the state at time $t$.\n",
131 | "\n",
132 | "These two assumptions make it possible to efficiently compute certain quantities that we may be interested in."
133 | ]
134 | },
135 | {
136 | "cell_type": "markdown",
137 | "metadata": {
138 | "id": "mRNhSK7LgEIS"
139 | },
140 | "source": [
141 | "## Components of an HMM\n",
142 | "An HMM has three sets of trainable parameters.\n",
143 | " \n"
144 | ]
145 | },
146 | {
147 | "cell_type": "markdown",
148 | "metadata": {
149 | "id": "7Pu3zm77vXwp"
150 | },
151 | "source": [
152 | "- The **transition model** is a square matrix $A$, where $A_{s, s'}$ represents $p(z_t = s|z_{t-1} = s')$, the probability of jumping from state $s'$ to state $s$. \n",
153 | "\n",
154 | "- The **emission model** $b_s(x_t)$ tells us $p(x_t|z_t = s)$, the probability of generating $x_t$ when the system is in state $s$. For discrete observations, which we will use in this notebook, the emission model is just a lookup table, with one row for each state, and one column for each observation. For real-valued observations, it is common to use a Gaussian mixture model or neural network to implement the emission model. \n",
155 | "\n",
156 | "- The **state priors** tell us $p(z_1 = s)$, the probability of starting in state $s$. We use $\\pi$ to denote the vector of state priors, so $\\pi_s$ is the state prior for state $s$.\n",
157 | "\n",
158 | "Let's program an HMM class in PyTorch."
159 | ]
160 | },
161 | {
162 | "cell_type": "code",
163 | "metadata": {
164 | "id": "aZbW6Pj0og7K"
165 | },
166 | "source": [
167 | "import torch\n",
168 | "import numpy as np\n",
169 | "\n",
170 | "class HMM(torch.nn.Module):\n",
171 | " \"\"\"\n",
172 | " Hidden Markov Model with discrete observations.\n",
173 | " \"\"\"\n",
174 | " def __init__(self, M, N):\n",
175 | " super(HMM, self).__init__()\n",
176 | " self.M = M # number of possible observations\n",
177 | " self.N = N # number of states\n",
178 | "\n",
179 | " # A\n",
180 | " self.transition_model = TransitionModel(self.N)\n",
181 | "\n",
182 | " # b(x_t)\n",
183 | " self.emission_model = EmissionModel(self.N,self.M)\n",
184 | "\n",
185 | " # pi\n",
186 | " self.unnormalized_state_priors = torch.nn.Parameter(torch.randn(self.N))\n",
187 | "\n",
188 | " # use the GPU\n",
189 | " self.is_cuda = torch.cuda.is_available()\n",
190 | " if self.is_cuda: self.cuda()\n",
191 | "\n",
192 | "class TransitionModel(torch.nn.Module):\n",
193 | " def __init__(self, N):\n",
194 | " super(TransitionModel, self).__init__()\n",
195 | " self.N = N\n",
196 | " self.unnormalized_transition_matrix = torch.nn.Parameter(torch.randn(N,N))\n",
197 | "\n",
198 | "class EmissionModel(torch.nn.Module):\n",
199 | " def __init__(self, N, M):\n",
200 | " super(EmissionModel, self).__init__()\n",
201 | " self.N = N\n",
202 | " self.M = M\n",
203 | " self.unnormalized_emission_matrix = torch.nn.Parameter(torch.randn(N,M))"
204 | ],
205 | "execution_count": 15,
206 | "outputs": []
207 | },
208 | {
209 | "cell_type": "markdown",
210 | "metadata": {
211 | "id": "eom3ueYtpXGo"
212 | },
213 | "source": [
214 | "To sample from the HMM, we start by picking a random initial state from the state prior distribution.\n",
215 | "\n",
216 | "Then, we sample an output from the emission distribution, sample a transition from the transition distribution, and repeat.\n",
217 | "\n",
218 | "(Notice that we pass the unnormalized model parameters through a softmax function to make them into probabilities.)\n"
219 | ]
220 | },
221 | {
222 | "cell_type": "code",
223 | "metadata": {
224 | "id": "BpgkwNyVwmyM"
225 | },
226 | "source": [
227 | "def sample(self, T=10):\n",
228 | " state_priors = torch.nn.functional.softmax(self.unnormalized_state_priors, dim=0)\n",
229 | " transition_matrix = torch.nn.functional.softmax(self.transition_model.unnormalized_transition_matrix, dim=0)\n",
230 | " emission_matrix = torch.nn.functional.softmax(self.emission_model.unnormalized_emission_matrix, dim=1)\n",
231 | "\n",
232 | " # sample initial state\n",
233 | " z_t = torch.distributions.categorical.Categorical(state_priors).sample().item()\n",
234 | " z = []; x = []\n",
235 | " z.append(z_t)\n",
236 | " for t in range(0,T):\n",
237 | " # sample emission\n",
238 | " x_t = torch.distributions.categorical.Categorical(emission_matrix[z_t]).sample().item()\n",
239 | " x.append(x_t)\n",
240 | "\n",
241 | " # sample transition\n",
242 | " z_t = torch.distributions.categorical.Categorical(transition_matrix[:,z_t]).sample().item()\n",
243 | " if t < T-1: z.append(z_t)\n",
244 | "\n",
245 | " return x, z\n",
246 | "\n",
247 | "# Add the sampling method to our HMM class\n",
248 | "HMM.sample = sample"
249 | ],
250 | "execution_count": 16,
251 | "outputs": []
252 | },
253 | {
254 | "cell_type": "markdown",
255 | "metadata": {
256 | "id": "ohsdYScawkRG"
257 | },
258 | "source": [
259 | "Let's try hard-coding an HMM for generating fake words. (We'll also add some helper functions for encoding and decoding strings.)\n",
260 | "\n",
261 | "We will assume that the system has one state for generating vowels and one state for generating consonants, and the transition matrix has 0s on the diagonal---in other words, the system cannot stay in the vowel state or the consonant state for one than one timestep; it has to switch.\n",
262 | "\n",
263 | "Since we pass the transition matrix through a softmax, to get 0s we set the unnormalized parameter values to $-\\infty$."
264 | ]
265 | },
266 | {
267 | "cell_type": "code",
268 | "metadata": {
269 | "id": "eyR7yv_3sBG3",
270 | "colab": {
271 | "base_uri": "https://localhost:8080/"
272 | },
273 | "outputId": "123309a6-ad66-4c6d-977a-60e3af957246"
274 | },
275 | "source": [
276 | "import string\n",
277 | "alphabet = string.ascii_lowercase\n",
278 | "\n",
279 | "def encode(s):\n",
280 | " \"\"\"\n",
281 | " Convert a string into a list of integers\n",
282 | " \"\"\"\n",
283 | " x = [alphabet.index(ss) for ss in s]\n",
284 | " return x\n",
285 | "\n",
286 | "def decode(x):\n",
287 | " \"\"\"\n",
288 | " Convert list of ints to string\n",
289 | " \"\"\"\n",
290 | " s = \"\".join([alphabet[xx] for xx in x])\n",
291 | " return s\n",
292 | "\n",
293 | "# Initialize the model\n",
294 | "model = HMM(M=len(alphabet), N=2) \n",
295 | "\n",
296 | "# Hard-wiring the parameters!\n",
297 | "# Let state 0 = consonant, state 1 = vowel\n",
298 | "for p in model.parameters():\n",
299 | " p.requires_grad = False # needed to do lines below\n",
300 | "model.unnormalized_state_priors[0] = 0. # Let's start with a consonant more frequently\n",
301 | "model.unnormalized_state_priors[1] = -0.5\n",
302 | "print(\"State priors:\", torch.nn.functional.softmax(model.unnormalized_state_priors, dim=0))\n",
303 | "\n",
304 | "# In state 0, only allow consonants; in state 1, only allow vowels\n",
305 | "vowel_indices = torch.tensor([alphabet.index(letter) for letter in \"aeiou\"])\n",
306 | "consonant_indices = torch.tensor([alphabet.index(letter) for letter in \"bcdfghjklmnpqrstvwxyz\"])\n",
307 | "model.emission_model.unnormalized_emission_matrix[0, vowel_indices] = -np.inf\n",
308 | "model.emission_model.unnormalized_emission_matrix[1, consonant_indices] = -np.inf \n",
309 | "print(\"Emission matrix:\", torch.nn.functional.softmax(model.emission_model.unnormalized_emission_matrix, dim=1))\n",
310 | "\n",
311 | "# Only allow vowel -> consonant and consonant -> vowel\n",
312 | "model.transition_model.unnormalized_transition_matrix[0,0] = -np.inf # consonant -> consonant\n",
313 | "model.transition_model.unnormalized_transition_matrix[0,1] = 0. # vowel -> consonant\n",
314 | "model.transition_model.unnormalized_transition_matrix[1,0] = 0. # consonant -> vowel\n",
315 | "model.transition_model.unnormalized_transition_matrix[1,1] = -np.inf # vowel -> vowel\n",
316 | "print(\"Transition matrix:\", torch.nn.functional.softmax(model.transition_model.unnormalized_transition_matrix, dim=0))\n",
317 | "\n"
318 | ],
319 | "execution_count": 17,
320 | "outputs": [
321 | {
322 | "output_type": "stream",
323 | "text": [
324 | "State priors: tensor([0.6225, 0.3775], device='cuda:0')\n",
325 | "Emission matrix: tensor([[0.0000, 0.0806, 0.0055, 0.0652, 0.0000, 0.0105, 0.0746, 0.0384, 0.0000,\n",
326 | " 0.0255, 0.0142, 0.0375, 0.0166, 0.0548, 0.0000, 0.0790, 0.0237, 0.0151,\n",
327 | " 0.0629, 0.0349, 0.0000, 0.1072, 0.0155, 0.1230, 0.0579, 0.0574],\n",
328 | " [0.2217, 0.0000, 0.0000, 0.0000, 0.1888, 0.0000, 0.0000, 0.0000, 0.1722,\n",
329 | " 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0870, 0.0000, 0.0000, 0.0000,\n",
330 | " 0.0000, 0.0000, 0.3303, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],\n",
331 | " device='cuda:0')\n",
332 | "Transition matrix: tensor([[0., 1.],\n",
333 | " [1., 0.]], device='cuda:0')\n"
334 | ],
335 | "name": "stdout"
336 | }
337 | ]
338 | },
339 | {
340 | "cell_type": "markdown",
341 | "metadata": {
342 | "id": "KFaYq8jDttmi"
343 | },
344 | "source": [
345 | "Try sampling from our hard-coded model:\n"
346 | ]
347 | },
348 | {
349 | "cell_type": "code",
350 | "metadata": {
351 | "id": "8latFMD7ua0X",
352 | "colab": {
353 | "base_uri": "https://localhost:8080/"
354 | },
355 | "outputId": "18529d60-cfee-421d-f49d-0fd281420b7b"
356 | },
357 | "source": [
358 | "# Sample some outputs\n",
359 | "for _ in range(4):\n",
360 | " sampled_x, sampled_z = model.sample(T=5)\n",
361 | " print(\"x:\", decode(sampled_x))\n",
362 | " print(\"z:\", sampled_z)"
363 | ],
364 | "execution_count": 18,
365 | "outputs": [
366 | {
367 | "output_type": "stream",
368 | "text": [
369 | "x: napax\n",
370 | "z: [0, 1, 0, 1, 0]\n",
371 | "x: ipoyo\n",
372 | "z: [1, 0, 1, 0, 1]\n",
373 | "x: upoye\n",
374 | "z: [1, 0, 1, 0, 1]\n",
375 | "x: hihiv\n",
376 | "z: [0, 1, 0, 1, 0]\n"
377 | ],
378 | "name": "stdout"
379 | }
380 | ]
381 | },
382 | {
383 | "cell_type": "markdown",
384 | "metadata": {
385 | "id": "hKzlTlfRgZod"
386 | },
387 | "source": [
388 | "## The Three Problems\n",
389 | "\n",
390 | "In a [classic tutorial](https://www.cs.cmu.edu/~cga/behavior/rabiner1.pdf) on HMMs, Lawrence Rabiner describes \"three problems\" that need to be solved before you can effectively use an HMM. They are:\n",
391 | "- Problem 1: How do we efficiently compute $p(\\mathbf{x})$?\n",
392 | "- Problem 2: How do we find the most likely state sequence $\\mathbf{z}$ that could have generated the data? \n",
393 | "- Problem 3: How do we train the model?\n",
394 | "\n",
395 | "In the rest of the notebook, we will see how to solve each problem and implement the solutions in PyTorch."
396 | ]
397 | },
398 | {
399 | "cell_type": "markdown",
400 | "metadata": {
401 | "id": "v_RfIAnmN2RZ"
402 | },
403 | "source": [
404 | "### Problem 1: How do we compute $p(\\mathbf{x})$?"
405 | ]
406 | },
407 | {
408 | "cell_type": "markdown",
409 | "metadata": {
410 | "id": "Z3zUUYH0giKV"
411 | },
412 | "source": [
413 | "\n",
414 | "#### *Why?*\n",
415 | "Why might we care about computing $p(\\mathbf{x})$? Here's two reasons.\n",
416 | "* Given two HMMs, $\\theta_1$ and $\\theta_2$, we can compute the likelihood of some data $\\mathbf{x}$ under each model, $p_{\\theta_1}(\\mathbf{x})$ and $p_{\\theta_2}(\\mathbf{x})$, to decide which model is a better fit to the data. \n",
417 | "\n",
418 | " (For example, given an HMM for English speech and an HMM for French speech, we could compute the likelihood given each model, and pick the model with the higher likelihood to infer whether the person is speaking English or French.)\n",
419 | "* Being able to compute $p(\\mathbf{x})$ gives us a way to train the model, as we will see later.\n",
420 | "\n",
421 | "#### *How?*\n",
422 | "Given that we want $p(\\mathbf{x})$, how do we compute it?\n",
423 | "\n",
424 | "We've assumed that the data is generated by visiting some sequence of states $\\mathbf{z}$ and picking an output $x_t$ for each $z_t$ from the emission distribution $p(x_t|z_t)$. So if we knew $\\mathbf{z}$, then the probability of $\\mathbf{x}$ could be computed as follows:\n",
425 | "\n",
426 | "$$p(\\mathbf{x}|\\mathbf{z}) = \\prod_{t} p(x_t|z_t) p(z_t|z_{t-1})$$\n",
427 | "\n",
428 | "However, we don't know $\\mathbf{z}$; it's hidden. But we do know the probability of any given $\\mathbf{z}$, independent of what we observe. So we could get the probability of $\\mathbf{x}$ by summing over the different possibilities for $\\mathbf{z}$, like this:\n",
429 | "\n",
430 | "$$p(\\mathbf{x}) = \\sum_{\\mathbf{z}} p(\\mathbf{x}|\\mathbf{z}) p(\\mathbf{z}) = \\sum_{\\mathbf{z}} \\prod_{t} p(x_t|z_t) p(z_t|z_{t-1})$$\n",
431 | "\n",
432 | "The problem is: if you try to take that sum directly, you will need to compute $N^T$ terms. This is impossible to do for anything but very short sequences. For example, let's say the sequence is of length $T=100$ and there are $N=2$ possible states. Then we would need to check $N^T = 2^{100} \\approx 10^{30}$ different possible state sequences.\n",
433 | "\n",
434 | "We need a way to compute $p(\\mathbf{x})$ that doesn't require us to explicitly calculate all $N^T$ terms. For this, we use the forward algorithm."
435 | ]
436 | },
437 | {
438 | "cell_type": "markdown",
439 | "metadata": {
440 | "id": "DrH0YdUAhS6J"
441 | },
442 | "source": [
443 | "________\n",
444 | "\n",
445 | "The Forward Algorithm\n",
446 | "\n",
447 | "> for $s=1 \\rightarrow N$:\\\n",
448 | "> $\\alpha_{s,1} := b_s(x_1) \\cdot \\pi_s$ \n",
449 | "> \n",
450 | "> for $t = 2 \\rightarrow T$:\\\n",
451 | "> for $s = 1 \\rightarrow N$:\\\n",
452 | "> \n",
453 | "> $\\alpha_{s,t} := b_s(x_t) \\cdot \\underset{s'}{\\sum} A_{s, s'} \\cdot \\alpha_{s',t-1} $\n",
454 | "> \n",
455 | "> $p(\\mathbf{x}) := \\underset{s}{\\sum} \\alpha_{s,T}$\\\n",
456 | "> return $p(\\mathbf{x})$\n",
457 | "________\n"
458 | ]
459 | },
460 | {
461 | "cell_type": "markdown",
462 | "metadata": {
463 | "id": "bAdpwRiMn8Vn"
464 | },
465 | "source": [
466 | "The forward algorithm is much faster than enumerating all $N^T$ possible state sequences: it requires only $O(N^2T)$ operations to run, since each step is mostly multiplying the vector of forward variables by the transition matrix. (And very often we can reduce that complexity even further, if the transition matrix is sparse.)\n",
467 | "\n",
468 | "There is one practical problem with the forward algorithm as presented above: it is prone to underflow due to multiplying a long chain of small numbers, since probabilities are always between 0 and 1. Instead, let's do everything in the log domain. In the log domain, a multiplication becomes a sum, and a sum becomes a [logsumexp](https://lorenlugosch.github.io/posts/2020/06/logsumexp/). "
469 | ]
470 | },
471 | {
472 | "cell_type": "markdown",
473 | "metadata": {
474 | "id": "FZ8VsLFxA3iT"
475 | },
476 | "source": [
477 | "________\n",
478 | "\n",
479 | "The Forward Algorithm (Log Domain)\n",
480 | "\n",
481 | "> for $s=1 \\rightarrow N$:\\\n",
482 | "> $\\text{log }\\alpha_{s,1} := \\text{log }b_s(x_1) + \\text{log }\\pi_s$ \n",
483 | "> \n",
484 | "> for $t = 2 \\rightarrow T$:\\\n",
485 | "> for $s = 1 \\rightarrow N$:\\\n",
486 | "> \n",
487 | "> $\\text{log }\\alpha_{s,t} := \\text{log }b_s(x_t) + \\underset{s'}{\\text{logsumexp}} \\left( \\text{log }A_{s, s'} + \\text{log }\\alpha_{s',t-1} \\right)$\n",
488 | "> \n",
489 | "> $\\text{log }p(\\mathbf{x}) := \\underset{s}{\\text{logsumexp}} \\left( \\text{log }\\alpha_{s,T} \\right)$\\\n",
490 | "> return $\\text{log }p(\\mathbf{x})$\n",
491 | "________"
492 | ]
493 | },
494 | {
495 | "cell_type": "markdown",
496 | "metadata": {
497 | "id": "g55ik6ZCEiJU"
498 | },
499 | "source": [
500 | "Now that we have a numerically stable version of the forward algorithm, let's implement it in PyTorch. "
501 | ]
502 | },
503 | {
504 | "cell_type": "code",
505 | "metadata": {
506 | "id": "3CMdK1EfE1SJ"
507 | },
508 | "source": [
509 | "def HMM_forward(self, x, T):\n",
510 | " \"\"\"\n",
511 | " x : IntTensor of shape (batch size, T_max)\n",
512 | " T : IntTensor of shape (batch size)\n",
513 | "\n",
514 | " Compute log p(x) for each example in the batch.\n",
515 | " T = length of each example\n",
516 | " \"\"\"\n",
517 | " if self.is_cuda:\n",
518 | " \tx = x.cuda()\n",
519 | " \tT = T.cuda()\n",
520 | "\n",
521 | " batch_size = x.shape[0]; T_max = x.shape[1]\n",
522 | " log_state_priors = torch.nn.functional.log_softmax(self.unnormalized_state_priors, dim=0)\n",
523 | " log_alpha = torch.zeros(batch_size, T_max, self.N)\n",
524 | " if self.is_cuda: log_alpha = log_alpha.cuda()\n",
525 | "\n",
526 | " log_alpha[:, 0, :] = self.emission_model(x[:,0]) + log_state_priors\n",
527 | " for t in range(1, T_max):\n",
528 | " log_alpha[:, t, :] = self.emission_model(x[:,t]) + self.transition_model(log_alpha[:, t-1, :])\n",
529 | "\n",
530 | " # Select the sum for the final timestep (each x may have different length).\n",
531 | " log_sums = log_alpha.logsumexp(dim=2)\n",
532 | " log_probs = torch.gather(log_sums, 1, T.view(-1,1) - 1)\n",
533 | " return log_probs\n",
534 | "\n",
535 | "def emission_model_forward(self, x_t):\n",
536 | " log_emission_matrix = torch.nn.functional.log_softmax(self.unnormalized_emission_matrix, dim=1)\n",
537 | " out = log_emission_matrix[:, x_t].transpose(0,1)\n",
538 | " return out\n",
539 | "\n",
540 | "def transition_model_forward(self, log_alpha):\n",
541 | " \"\"\"\n",
542 | " log_alpha : Tensor of shape (batch size, N)\n",
543 | " Multiply previous timestep's alphas by transition matrix (in log domain)\n",
544 | " \"\"\"\n",
545 | " log_transition_matrix = torch.nn.functional.log_softmax(self.unnormalized_transition_matrix, dim=0)\n",
546 | "\n",
547 | " # Matrix multiplication in the log domain\n",
548 | " out = log_domain_matmul(log_transition_matrix, log_alpha.transpose(0,1)).transpose(0,1)\n",
549 | " return out\n",
550 | "\n",
551 | "def log_domain_matmul(log_A, log_B):\n",
552 | "\t\"\"\"\n",
553 | "\tlog_A : m x n\n",
554 | "\tlog_B : n x p\n",
555 | "\toutput : m x p matrix\n",
556 | "\n",
557 | "\tNormally, a matrix multiplication\n",
558 | "\tcomputes out_{i,j} = sum_k A_{i,k} x B_{k,j}\n",
559 | "\n",
560 | "\tA log domain matrix multiplication\n",
561 | "\tcomputes out_{i,j} = logsumexp_k log_A_{i,k} + log_B_{k,j}\n",
562 | "\t\"\"\"\n",
563 | "\tm = log_A.shape[0]\n",
564 | "\tn = log_A.shape[1]\n",
565 | "\tp = log_B.shape[1]\n",
566 | "\n",
567 | "\t# log_A_expanded = torch.stack([log_A] * p, dim=2)\n",
568 | "\t# log_B_expanded = torch.stack([log_B] * m, dim=0)\n",
569 | " # fix for PyTorch > 1.5 by egaznep on Github:\n",
570 | "\tlog_A_expanded = torch.reshape(log_A, (m,n,1))\n",
571 | "\tlog_B_expanded = torch.reshape(log_B, (1,n,p))\n",
572 | "\n",
573 | "\telementwise_sum = log_A_expanded + log_B_expanded\n",
574 | "\tout = torch.logsumexp(elementwise_sum, dim=1)\n",
575 | "\n",
576 | "\treturn out\n",
577 | "\n",
578 | "TransitionModel.forward = transition_model_forward\n",
579 | "EmissionModel.forward = emission_model_forward\n",
580 | "HMM.forward = HMM_forward"
581 | ],
582 | "execution_count": 19,
583 | "outputs": []
584 | },
585 | {
586 | "cell_type": "markdown",
587 | "metadata": {
588 | "id": "y-fNnZfqGb1m"
589 | },
590 | "source": [
591 | "Try running the forward algorithm on our vowels/consonants model from before:"
592 | ]
593 | },
594 | {
595 | "cell_type": "code",
596 | "metadata": {
597 | "id": "8rMAmf-UGhbw",
598 | "colab": {
599 | "base_uri": "https://localhost:8080/"
600 | },
601 | "outputId": "a6b57c5a-2d50-4214-b4ee-3e29a67904b1"
602 | },
603 | "source": [
604 | "x = torch.stack( [torch.tensor(encode(\"cat\"))] )\n",
605 | "T = torch.tensor([3])\n",
606 | "print(model.forward(x, T))\n",
607 | "\n",
608 | "x = torch.stack( [torch.tensor(encode(\"aba\")), torch.tensor(encode(\"abb\"))] )\n",
609 | "T = torch.tensor([3,3])\n",
610 | "print(model.forward(x, T))"
611 | ],
612 | "execution_count": 20,
613 | "outputs": [
614 | {
615 | "output_type": "stream",
616 | "text": [
617 | "tensor([[-10.5390]], device='cuda:0')\n",
618 | "tensor([[-6.5049],\n",
619 | " [ -inf]], device='cuda:0')\n"
620 | ],
621 | "name": "stdout"
622 | }
623 | ]
624 | },
625 | {
626 | "cell_type": "markdown",
627 | "metadata": {
628 | "id": "95TB2gvNHuLn"
629 | },
630 | "source": [
631 | "When using the vowel <-> consonant HMM from above, notice that the forward algorithm returns $-\\infty$ for $\\mathbf{x} = \\text{\"abb\"}$. That's because our transition matrix says the probability of vowel -> vowel and consonant -> consonant is 0, so the probability of $\\text{\"abb\"}$ happening is 0, and thus the log probability is $-\\infty$."
632 | ]
633 | },
634 | {
635 | "cell_type": "markdown",
636 | "metadata": {
637 | "id": "qBCrFobsEM8X"
638 | },
639 | "source": [
640 | "#### *Side note: deriving the forward algorithm*\n",
641 | "\n",
642 | "If you're interested in understanding how the forward algorithm actually computes $p(\\mathbf{x})$, read this section; if not, skip to the next part on \"Problem 2\" (finding the most likely state sequence)."
643 | ]
644 | },
645 | {
646 | "cell_type": "markdown",
647 | "metadata": {
648 | "id": "CpHWWKcxhjkx"
649 | },
650 | "source": [
651 | "\n",
652 | "\n",
653 | "To derive the forward algorithm, start by deriving the forward variable:\n",
654 | "\n",
655 | "$$\\begin{align} \n",
656 | " \\alpha_{s,t} &= p(x_1, x_2, \\dots, x_t, z_t=s) \\\\\n",
657 | " &= p(x_t | x_1, x_2, \\dots, x_{t-1}, z_t = s) \\cdot p(x_1, x_2, \\dots, x_{t-1}, z_t = s) \\\\ \n",
658 | " &= p(x_t | z_t = s) \\cdot p(x_1, x_2, \\dots, x_{t-1}, z_t = s) \\\\\n",
659 | " &= p(x_t | z_t = s) \\cdot \\left( \\sum_{s'} p(x_1, x_2, \\dots, x_{t-1}, z_{t-1}=s', z_t = s) \\right)\\\\\n",
660 | " &= p(x_t | z_t = s) \\cdot \\left( \\sum_{s'} p(z_t = s | x_1, x_2, \\dots, x_{t-1}, z_{t-1}=s') \\cdot p(x_1, x_2, \\dots, x_{t-1}, z_{t-1}=s') \\right)\\\\\n",
661 | " &= \\underbrace{p(x_t | z_t = s)}_{\\text{emission model}} \\cdot \\left( \\sum_{s'} \\underbrace{p(z_t = s | z_{t-1}=s')}_{\\text{transition model}} \\cdot \\underbrace{p(x_1, x_2, \\dots, x_{t-1}, z_{t-1}=s')}_{\\text{forward variable for previous timestep}} \\right)\\\\\n",
662 | " &= b_s(x_t) \\cdot \\left( \\sum_{s'} A_{s, s'} \\cdot \\alpha_{s',t-1} \\right)\n",
663 | " \\end{align}$$\n",
664 | "\n",
665 | "I'll explain how to get to each line of this equation from the previous line. \n",
666 | "\n",
667 | "Line 1 is the definition of the forward variable $\\alpha_{s,t}$.\n",
668 | "\n",
669 | "Line 2 is the chain rule ($p(A,B) = p(A|B) \\cdot p(B)$, where $A$ is $x_t$ and $B$ is all the other variables).\n",
670 | "\n",
671 | "In Line 3, we apply Assumption 2: the probability of observation $x_t$ depends only on the current state $z_t$.\n",
672 | "\n",
673 | "In Line 4, we marginalize over all the possible states in the previous timestep $t-1$.\n",
674 | "\n",
675 | "In Line 5, we apply the chain rule again.\n",
676 | "\n",
677 | "In Line 6, we apply Assumption 1: the current state depends only on the previous state.\n",
678 | "\n",
679 | "In Line 7, we substitute in the emission probability, the transition probability, and the forward variable for the previous timestep, to get the complete recursion."
680 | ]
681 | },
682 | {
683 | "cell_type": "markdown",
684 | "metadata": {
685 | "id": "kh1ovNjWDbIA"
686 | },
687 | "source": [
688 | "The formula above can be used for $t = 2 \\rightarrow T$. At $t=1$, there is no previous state, so instead of the transition matrix $A$, we use the state priors $\\pi$, which tell us the probability of starting in each state. Thus for $t=1$, the forward variables are computed as follows:\n",
689 | "\n",
690 | "$$\\begin{align} \n",
691 | "\\alpha_{s,1} &= p(x_1, z_1=s) \\\\\n",
692 | " &= p(x_1 | z_1 = s) \\cdot p(z_1 = s) \\\\ \n",
693 | "&= b_s(x_1) \\cdot \\pi_s\n",
694 | "\\end{align}$$"
695 | ]
696 | },
697 | {
698 | "cell_type": "markdown",
699 | "metadata": {
700 | "id": "RRzSqkRkEWKX"
701 | },
702 | "source": [
703 | "Finally, to compute $p(\\mathbf{x}) = p(x_1, x_2, \\dots, x_T)$, we marginalize over $\\alpha_{s,T}$, the forward variables computed in the last timestep:\n",
704 | "\n",
705 | "$$\\begin{align*} \n",
706 | "p(\\mathbf{x}) &= \\sum_{s} p(x_1, x_2, \\dots, x_T, z_T = s) \\\\ \n",
707 | "&= \\sum_{s} \\alpha_{s,T}\n",
708 | "\\end{align*}$$"
709 | ]
710 | },
711 | {
712 | "cell_type": "markdown",
713 | "metadata": {
714 | "id": "qLBU8Iu7I5Tb"
715 | },
716 | "source": [
717 | "You can get from this formulation to the log domain formulation by taking the log of the forward variable, and using these identities:\n",
718 | "- $\\text{log }(a \\cdot b) = \\text{log }a + \\text{log }b$\n",
719 | "- $\\text{log }(a + b) = \\text{log }(e^{\\text{log }a} + e^{\\text{log }b}) = \\text{logsumexp}(\\text{log }a, \\text{log }b)$"
720 | ]
721 | },
722 | {
723 | "cell_type": "markdown",
724 | "metadata": {
725 | "id": "bxivzF8hgpiW"
726 | },
727 | "source": [
728 | "### Problem 2: How do we compute $\\underset{\\mathbf{z}}{\\text{argmax }} p(\\mathbf{z}|\\mathbf{x})$?"
729 | ]
730 | },
731 | {
732 | "cell_type": "markdown",
733 | "metadata": {
734 | "id": "c1Kv2yyiN7SX"
735 | },
736 | "source": [
737 | "Given an observation sequence $\\mathbf{x}$, we may want to find the most likely sequence of states that could have generated $\\mathbf{x}$. (Given the sequence of selfies, we want to infer what cities the friend visited.) In other words, we want $\\underset{\\mathbf{z}}{\\text{argmax }} p(\\mathbf{z}|\\mathbf{x})$.\n",
738 | "\n",
739 | "We can use Bayes' rule to rewrite this expression:\n",
740 | " $$\\begin{align*} \n",
741 | " \\underset{\\mathbf{z}}{\\text{argmax }} p(\\mathbf{z}|\\mathbf{x}) &= \\underset{\\mathbf{z}}{\\text{argmax }} \\frac{p(\\mathbf{x}|\\mathbf{z}) p(\\mathbf{z})}{p(\\mathbf{x})} \\\\ \n",
742 | " &= \\underset{\\mathbf{z}}{\\text{argmax }} p(\\mathbf{x}|\\mathbf{z}) p(\\mathbf{z})\n",
743 | " \\end{align*}$$\n",
744 | "\n",
745 | "Hmm! That last expression, $\\underset{\\mathbf{z}}{\\text{argmax }} p(\\mathbf{x}|\\mathbf{z}) p(\\mathbf{z})$, looks suspiciously similar to the intractable expression we encountered before introducing the forward algorithm, $\\underset{\\mathbf{z}}{\\sum} p(\\mathbf{x}|\\mathbf{z}) p(\\mathbf{z})$.\n",
746 | "\n",
747 | "And indeed, just as the intractable *sum* over all $\\mathbf{z}$ can be implemented efficiently using the forward algorithm, so too this intractable *argmax* can be implemented efficiently using a similar divide-and-conquer algorithm: the legendary Viterbi algorithm!"
748 | ]
749 | },
750 | {
751 | "cell_type": "markdown",
752 | "metadata": {
753 | "id": "niKZEX5xWeWR"
754 | },
755 | "source": [
756 | "________\n",
757 | "\n",
758 | "The Viterbi Algorithm\n",
759 | "\n",
760 | "> for $s=1 \\rightarrow N$:\\\n",
761 | "> $\\delta_{s,1} := b_s(x_1) \\cdot \\pi_s$\\\n",
762 | "> $\\psi_{s,1} := 0$\n",
763 | ">\n",
764 | "> for $t = 2 \\rightarrow T$:\\\n",
765 | "> for $s = 1 \\rightarrow N$:\\\n",
766 | "> $\\delta_{s,t} := b_s(x_t) \\cdot \\left( \\underset{s'}{\\text{max }} A_{s, s'} \\cdot \\delta_{s',t-1} \\right)$\\\n",
767 | " $\\psi_{s,t} := \\underset{s'}{\\text{argmax }} A_{s, s'} \\cdot \\delta_{s',t-1}$\n",
768 | "> \n",
769 | "> $z_T^* := \\underset{s}{\\text{argmax }} \\delta_{s,T}$\\\n",
770 | "> for $t = T-1 \\rightarrow 1$:\\\n",
771 | " $z_{t}^* := \\psi_{z_{t+1}^*,t+1}$\n",
772 | "> \n",
773 | "> $\\mathbf{z}^* := \\{z_{1}^*, \\dots, z_{T}^* \\}$\\\n",
774 | "return $\\mathbf{z}^*$\n",
775 | "________"
776 | ]
777 | },
778 | {
779 | "cell_type": "markdown",
780 | "metadata": {
781 | "id": "UcHVTCucZV6K"
782 | },
783 | "source": [
784 | "The Viterbi algorithm looks somewhat gnarlier than the forward algorithm, but it is essentially the same algorithm, with two tweaks: 1) instead of taking the sum over previous states, we take the max; and 2) we record the argmax of the previous states in a table, and loop back over this table at the end to get $\\mathbf{z}^*$, the most likely state sequence. (And like the forward algorithm, we should run the Viterbi algorithm in the log domain for better numerical stability.) "
785 | ]
786 | },
787 | {
788 | "cell_type": "markdown",
789 | "metadata": {
790 | "id": "NlN7IY_JZ5A-"
791 | },
792 | "source": [
793 | "Let's add the Viterbi algorithm to our PyTorch model:"
794 | ]
795 | },
796 | {
797 | "cell_type": "code",
798 | "metadata": {
799 | "id": "qeDG8DVmZ-P0"
800 | },
801 | "source": [
802 | "def viterbi(self, x, T):\n",
803 | " \"\"\"\n",
804 | " x : IntTensor of shape (batch size, T_max)\n",
805 | " T : IntTensor of shape (batch size)\n",
806 | " Find argmax_z log p(x|z) for each (x) in the batch.\n",
807 | " \"\"\"\n",
808 | " if self.is_cuda:\n",
809 | " x = x.cuda()\n",
810 | " T = T.cuda()\n",
811 | "\n",
812 | " batch_size = x.shape[0]; T_max = x.shape[1]\n",
813 | " log_state_priors = torch.nn.functional.log_softmax(self.unnormalized_state_priors, dim=0)\n",
814 | " log_delta = torch.zeros(batch_size, T_max, self.N).float()\n",
815 | " psi = torch.zeros(batch_size, T_max, self.N).long()\n",
816 | " if self.is_cuda:\n",
817 | " log_delta = log_delta.cuda()\n",
818 | " psi = psi.cuda()\n",
819 | "\n",
820 | " log_delta[:, 0, :] = self.emission_model(x[:,0]) + log_state_priors\n",
821 | " for t in range(1, T_max):\n",
822 | " max_val, argmax_val = self.transition_model.maxmul(log_delta[:, t-1, :])\n",
823 | " log_delta[:, t, :] = self.emission_model(x[:,t]) + max_val\n",
824 | " psi[:, t, :] = argmax_val\n",
825 | "\n",
826 | " # Get the log probability of the best path\n",
827 | " log_max = log_delta.max(dim=2)[0]\n",
828 | " best_path_scores = torch.gather(log_max, 1, T.view(-1,1) - 1)\n",
829 | "\n",
830 | " # This next part is a bit tricky to parallelize across the batch,\n",
831 | " # so we will do it separately for each example.\n",
832 | " z_star = []\n",
833 | " for i in range(0, batch_size):\n",
834 | " z_star_i = [ log_delta[i, T[i] - 1, :].max(dim=0)[1].item() ]\n",
835 | " for t in range(T[i] - 1, 0, -1):\n",
836 | " z_t = psi[i, t, z_star_i[0]].item()\n",
837 | " z_star_i.insert(0, z_t)\n",
838 | "\n",
839 | " z_star.append(z_star_i)\n",
840 | "\n",
841 | " return z_star, best_path_scores # return both the best path and its log probability\n",
842 | "\n",
843 | "def transition_model_maxmul(self, log_alpha):\n",
844 | " log_transition_matrix = torch.nn.functional.log_softmax(self.unnormalized_transition_matrix, dim=0)\n",
845 | "\n",
846 | " out1, out2 = maxmul(log_transition_matrix, log_alpha.transpose(0,1))\n",
847 | " return out1.transpose(0,1), out2.transpose(0,1)\n",
848 | "\n",
849 | "def maxmul(log_A, log_B):\n",
850 | "\t\"\"\"\n",
851 | "\tlog_A : m x n\n",
852 | "\tlog_B : n x p\n",
853 | "\toutput : m x p matrix\n",
854 | "\n",
855 | "\tSimilar to the log domain matrix multiplication,\n",
856 | "\tthis computes out_{i,j} = max_k log_A_{i,k} + log_B_{k,j}\n",
857 | "\t\"\"\"\n",
858 | "\tm = log_A.shape[0]\n",
859 | "\tn = log_A.shape[1]\n",
860 | "\tp = log_B.shape[1]\n",
861 | "\n",
862 | "\tlog_A_expanded = torch.stack([log_A] * p, dim=2)\n",
863 | "\tlog_B_expanded = torch.stack([log_B] * m, dim=0)\n",
864 | "\n",
865 | "\telementwise_sum = log_A_expanded + log_B_expanded\n",
866 | "\tout1,out2 = torch.max(elementwise_sum, dim=1)\n",
867 | "\n",
868 | "\treturn out1,out2\n",
869 | "\n",
870 | "TransitionModel.maxmul = transition_model_maxmul\n",
871 | "HMM.viterbi = viterbi"
872 | ],
873 | "execution_count": 21,
874 | "outputs": []
875 | },
876 | {
877 | "cell_type": "markdown",
878 | "metadata": {
879 | "id": "uTGOaeXbaWie"
880 | },
881 | "source": [
882 | "Try running Viterbi on an input sequence, given the vowel/consonant HMM:"
883 | ]
884 | },
885 | {
886 | "cell_type": "code",
887 | "metadata": {
888 | "id": "zeOTbaIMc23d",
889 | "colab": {
890 | "base_uri": "https://localhost:8080/"
891 | },
892 | "outputId": "d179c535-7b5c-42ea-b348-056b4e7efdd7"
893 | },
894 | "source": [
895 | "x = torch.stack( [torch.tensor(encode(\"aba\")), torch.tensor(encode(\"abb\"))] )\n",
896 | "T = torch.tensor([3,3])\n",
897 | "print(model.viterbi(x, T))"
898 | ],
899 | "execution_count": 22,
900 | "outputs": [
901 | {
902 | "output_type": "stream",
903 | "text": [
904 | "([[1, 0, 1], [1, 0, 0]], tensor([[-6.5049],\n",
905 | " [ -inf]], device='cuda:0'))\n"
906 | ],
907 | "name": "stdout"
908 | }
909 | ]
910 | },
911 | {
912 | "cell_type": "markdown",
913 | "metadata": {
914 | "id": "fKr8YlafdzBx"
915 | },
916 | "source": [
917 | "For $\\mathbf{x} = \\text{\"aba\"}$, the Viterbi algorithm returns $\\mathbf{z}^* = \\{1,0,1\\}$. This corresponds to \"vowel, consonant, vowel\" according to the way we defined the states above, which is correct for this input sequence. Yay!\n",
918 | "\n",
919 | "For $\\mathbf{x} = \\text{\"abb\"}$, the Viterbi algorithm still returns a $\\mathbf{z}^*$, but we know this is gibberish because \"vowel, consonant, consonant\" is impossible under this HMM, and indeed the log probability of this path is $-\\infty$."
920 | ]
921 | },
922 | {
923 | "cell_type": "markdown",
924 | "metadata": {
925 | "id": "nCWw0_WienO_"
926 | },
927 | "source": [
928 | "Let's compare the \"forward score\" (the log probability of all possible paths, returned by the forward algorithm) with the \"Viterbi score\" (the log probability of the maximum likelihood path, returned by the Viterbi algorithm):"
929 | ]
930 | },
931 | {
932 | "cell_type": "code",
933 | "metadata": {
934 | "id": "L9fBOHvdeqWC",
935 | "colab": {
936 | "base_uri": "https://localhost:8080/"
937 | },
938 | "outputId": "25808413-b061-414b-aa49-c5403be214db"
939 | },
940 | "source": [
941 | "print(model.forward(x, T))\n",
942 | "print(model.viterbi(x, T)[1])"
943 | ],
944 | "execution_count": 23,
945 | "outputs": [
946 | {
947 | "output_type": "stream",
948 | "text": [
949 | "tensor([[-6.5049],\n",
950 | " [ -inf]], device='cuda:0')\n",
951 | "tensor([[-6.5049],\n",
952 | " [ -inf]], device='cuda:0')\n"
953 | ],
954 | "name": "stdout"
955 | }
956 | ]
957 | },
958 | {
959 | "cell_type": "markdown",
960 | "metadata": {
961 | "id": "InF6PJVOfHwH"
962 | },
963 | "source": [
964 | "The two scores are the same! That's because in this instance there is only one possible path through the HMM, so the probability of the most likely path is the same as the sum of the probabilities of all possible paths.\n",
965 | "\n",
966 | "In general, though, the forward score and Viterbi score will always be somewhat close. This is because of a property of the $\\text{logsumexp}$ function: $\\text{logsumexp}(\\mathbf{x}) \\approx \\max (\\mathbf{x})$. ($\\text{logsumexp}$ is sometimes referred to as the \"smooth maximum\" function.)"
967 | ]
968 | },
969 | {
970 | "cell_type": "code",
971 | "metadata": {
972 | "id": "x__70tB6gnkF",
973 | "colab": {
974 | "base_uri": "https://localhost:8080/"
975 | },
976 | "outputId": "e75db689-519f-4208-9238-794a16167224"
977 | },
978 | "source": [
979 | "x = torch.tensor([1., 2., 3.])\n",
980 | "print(x.max(dim=0)[0])\n",
981 | "print(x.logsumexp(dim=0))"
982 | ],
983 | "execution_count": 24,
984 | "outputs": [
985 | {
986 | "output_type": "stream",
987 | "text": [
988 | "tensor(3.)\n",
989 | "tensor(3.4076)\n"
990 | ],
991 | "name": "stdout"
992 | }
993 | ]
994 | },
995 | {
996 | "cell_type": "markdown",
997 | "metadata": {
998 | "id": "SvFtiWhzgy0V"
999 | },
1000 | "source": [
1001 | "### Problem 3: How do we train the model?\n",
1002 | "\n",
1003 | "\n",
1004 | "\n"
1005 | ]
1006 | },
1007 | {
1008 | "cell_type": "markdown",
1009 | "metadata": {
1010 | "id": "r3JaykRalSBZ"
1011 | },
1012 | "source": [
1013 | "Earlier, we hard-coded an HMM to have certain behavior. What we would like to do instead is have the HMM learn to model the data on its own. And while it is possible to use supervised learning with an HMM (by hard-coding the emission model or the transition model) so that the states have a particular interpretation, the really cool thing about HMMs is that they are naturally unsupervised learners, so they can learn to use their different states to represent different patterns in the data, without the programmer needing to indicate what each state means."
1014 | ]
1015 | },
1016 | {
1017 | "cell_type": "markdown",
1018 | "metadata": {
1019 | "id": "8K471fT4N-PR"
1020 | },
1021 | "source": [
1022 | "Like many machine learning models, an HMM can be trained using maximum likelihood estimation, i.e.:\n",
1023 | "\n",
1024 | "$$\\theta^* = \\underset{\\theta}{\\text{argmin }} -\\sum_{\\mathbf{x}^i}\\text{log }p_{\\theta}(\\mathbf{x}^i)$$\n",
1025 | "\n",
1026 | "where $\\mathbf{x}^1, \\mathbf{x}^2, \\dots$ are training examples. \n",
1027 | "\n",
1028 | "The standard method for doing this is the Expectation-Maximization (EM) algorithm, which for HMMs is also called the \"Baum-Welch\" algorithm. In EM training, we alternate between an \"E-step\", where we estimate the values of the latent variables, and an \"M-step\", where the model parameters are updated given the estimated latent variables. (Think $k$-means, where you guess which cluster each data point belongs to, then reestimate where the clusters are, and repeat.) The EM algorithm has some nice properties: it is guaranteed at each step to decrease the loss function, and the E-step and M-step may have an exact closed form solution, in which case no pesky learning rates are required.\n",
1029 | "\n",
1030 | "But because the HMM forward algorithm is differentiable with respect to all the model parameters, we can also just take advantage of automatic differentiation methods in libraries like PyTorch and try to minimize $-\\text{log }p_{\\theta}(\\mathbf{x})$ directly, by backpropagating through the forward algorithm and running stochastic gradient descent. That means we don't need to write any additional HMM code to implement training: `loss.backward()` is all you need."
1031 | ]
1032 | },
1033 | {
1034 | "cell_type": "markdown",
1035 | "metadata": {
1036 | "id": "aVh0-369qZDC"
1037 | },
1038 | "source": [
1039 | "Here we will implement SGD training for an HMM in PyTorch. First, some helper classes:"
1040 | ]
1041 | },
1042 | {
1043 | "cell_type": "code",
1044 | "metadata": {
1045 | "id": "KqiFobGHwdzc"
1046 | },
1047 | "source": [
1048 | "import torch.utils.data\n",
1049 | "from collections import Counter\n",
1050 | "from sklearn.model_selection import train_test_split\n",
1051 | "\n",
1052 | "class TextDataset(torch.utils.data.Dataset):\n",
1053 | " def __init__(self, lines):\n",
1054 | " self.lines = lines # list of strings\n",
1055 | " collate = Collate() # function for generating a minibatch from strings\n",
1056 | " self.loader = torch.utils.data.DataLoader(self, batch_size=1024, num_workers=1, shuffle=True, collate_fn=collate)\n",
1057 | "\n",
1058 | " def __len__(self):\n",
1059 | " return len(self.lines)\n",
1060 | "\n",
1061 | " def __getitem__(self, idx):\n",
1062 | " line = self.lines[idx].lstrip(\" \").rstrip(\"\\n\").rstrip(\" \").rstrip(\"\\n\")\n",
1063 | " return line\n",
1064 | "\n",
1065 | "class Collate:\n",
1066 | " def __init__(self):\n",
1067 | " pass\n",
1068 | "\n",
1069 | " def __call__(self, batch):\n",
1070 | " \"\"\"\n",
1071 | " Returns a minibatch of strings, padded to have the same length.\n",
1072 | " \"\"\"\n",
1073 | " x = []\n",
1074 | " batch_size = len(batch)\n",
1075 | " for index in range(batch_size):\n",
1076 | " x_ = batch[index]\n",
1077 | "\n",
1078 | " # convert letters to integers\n",
1079 | " x.append(encode(x_))\n",
1080 | "\n",
1081 | " # pad all sequences with 0 to have same length\n",
1082 | " x_lengths = [len(x_) for x_ in x]\n",
1083 | " T = max(x_lengths)\n",
1084 | " for index in range(batch_size):\n",
1085 | " x[index] += [0] * (T - len(x[index]))\n",
1086 | " x[index] = torch.tensor(x[index])\n",
1087 | "\n",
1088 | " # stack into single tensor\n",
1089 | " x = torch.stack(x)\n",
1090 | " x_lengths = torch.tensor(x_lengths)\n",
1091 | " return (x,x_lengths)"
1092 | ],
1093 | "execution_count": 25,
1094 | "outputs": []
1095 | },
1096 | {
1097 | "cell_type": "markdown",
1098 | "metadata": {
1099 | "id": "YpDpwnPnAEA9"
1100 | },
1101 | "source": [
1102 | "Let's load some training/testing data. By default, this will use the unix \"words\" file, but you could also use your own text file."
1103 | ]
1104 | },
1105 | {
1106 | "cell_type": "code",
1107 | "metadata": {
1108 | "id": "52NqFHg8ANsB",
1109 | "colab": {
1110 | "base_uri": "https://localhost:8080/"
1111 | },
1112 | "outputId": "18754e86-1d8c-4e85-a930-827a5d49793d"
1113 | },
1114 | "source": [
1115 | "!wget https://raw.githubusercontent.com/lorenlugosch/pytorch_HMM/master/data/train/training.txt\n",
1116 | "\n",
1117 | "filename = \"training.txt\"\n",
1118 | "\n",
1119 | "with open(filename, \"r\") as f:\n",
1120 | " lines = f.readlines() # each line of lines will have one word\n",
1121 | "\n",
1122 | "alphabet = list(Counter((\"\".join(lines))).keys())\n",
1123 | "train_lines, valid_lines = train_test_split(lines, test_size=0.1, random_state=42)\n",
1124 | "train_dataset = TextDataset(train_lines)\n",
1125 | "valid_dataset = TextDataset(valid_lines)\n",
1126 | "\n",
1127 | "M = len(alphabet)"
1128 | ],
1129 | "execution_count": 26,
1130 | "outputs": [
1131 | {
1132 | "output_type": "stream",
1133 | "text": [
1134 | "--2021-03-20 18:38:40-- https://raw.githubusercontent.com/lorenlugosch/pytorch_HMM/master/data/train/training.txt\n",
1135 | "Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.111.133, 185.199.110.133, 185.199.108.133, ...\n",
1136 | "Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.111.133|:443... connected.\n",
1137 | "HTTP request sent, awaiting response... 200 OK\n",
1138 | "Length: 2493109 (2.4M) [text/plain]\n",
1139 | "Saving to: ‘training.txt’\n",
1140 | "\n",
1141 | "training.txt 100%[===================>] 2.38M --.-KB/s in 0.02s \n",
1142 | "\n",
1143 | "2021-03-20 18:38:40 (102 MB/s) - ‘training.txt’ saved [2493109/2493109]\n",
1144 | "\n"
1145 | ],
1146 | "name": "stdout"
1147 | }
1148 | ]
1149 | },
1150 | {
1151 | "cell_type": "markdown",
1152 | "metadata": {
1153 | "id": "H0AqmyrK7IUn"
1154 | },
1155 | "source": [
1156 | "We will use a Trainer class for training and testing the model:\n",
1157 | "\n"
1158 | ]
1159 | },
1160 | {
1161 | "cell_type": "code",
1162 | "metadata": {
1163 | "id": "iypy_neX9cpq"
1164 | },
1165 | "source": [
1166 | "from tqdm import tqdm # for displaying progress bar\n",
1167 | "\n",
1168 | "class Trainer:\n",
1169 | " def __init__(self, model, lr):\n",
1170 | " self.model = model\n",
1171 | " self.lr = lr\n",
1172 | " self.optimizer = torch.optim.Adam(model.parameters(), lr=self.lr, weight_decay=0.00001)\n",
1173 | " \n",
1174 | " def train(self, dataset):\n",
1175 | " train_loss = 0\n",
1176 | " num_samples = 0\n",
1177 | " self.model.train()\n",
1178 | " print_interval = 50\n",
1179 | " for idx, batch in enumerate(tqdm(dataset.loader)):\n",
1180 | " x,T = batch\n",
1181 | " batch_size = len(x)\n",
1182 | " num_samples += batch_size\n",
1183 | " log_probs = self.model(x,T)\n",
1184 | " loss = -log_probs.mean()\n",
1185 | " self.optimizer.zero_grad()\n",
1186 | " loss.backward()\n",
1187 | " self.optimizer.step()\n",
1188 | " train_loss += loss.cpu().data.numpy().item() * batch_size\n",
1189 | " if idx % print_interval == 0:\n",
1190 | " print(\"loss:\", loss.item())\n",
1191 | " for _ in range(5):\n",
1192 | " sampled_x, sampled_z = self.model.sample()\n",
1193 | " print(decode(sampled_x))\n",
1194 | " print(sampled_z)\n",
1195 | " train_loss /= num_samples\n",
1196 | " return train_loss\n",
1197 | "\n",
1198 | " def test(self, dataset):\n",
1199 | " test_loss = 0\n",
1200 | " num_samples = 0\n",
1201 | " self.model.eval()\n",
1202 | " print_interval = 50\n",
1203 | " for idx, batch in enumerate(dataset.loader):\n",
1204 | " x,T = batch\n",
1205 | " batch_size = len(x)\n",
1206 | " num_samples += batch_size\n",
1207 | " log_probs = self.model(x,T)\n",
1208 | " loss = -log_probs.mean()\n",
1209 | " test_loss += loss.cpu().data.numpy().item() * batch_size\n",
1210 | " if idx % print_interval == 0:\n",
1211 | " print(\"loss:\", loss.item())\n",
1212 | " sampled_x, sampled_z = self.model.sample()\n",
1213 | " print(decode(sampled_x))\n",
1214 | " print(sampled_z)\n",
1215 | " test_loss /= num_samples\n",
1216 | " return test_loss"
1217 | ],
1218 | "execution_count": 27,
1219 | "outputs": []
1220 | },
1221 | {
1222 | "cell_type": "markdown",
1223 | "metadata": {
1224 | "id": "mUR8qbHm9dMg"
1225 | },
1226 | "source": [
1227 | "Finally, initialize the model and run the main training loop. Every 50 batches, the code will produce a few samples from the model. Over time, these samples should look more and more realistic."
1228 | ]
1229 | },
1230 | {
1231 | "cell_type": "code",
1232 | "metadata": {
1233 | "id": "1-NGIK1Q9g2C",
1234 | "colab": {
1235 | "base_uri": "https://localhost:8080/"
1236 | },
1237 | "outputId": "71b7ed8f-e021-41f1-c043-cadcb3df8b07"
1238 | },
1239 | "source": [
1240 | "# Initialize model\n",
1241 | "model = HMM(N=64, M=M)\n",
1242 | "\n",
1243 | "# Train the model\n",
1244 | "num_epochs = 10\n",
1245 | "trainer = Trainer(model, lr=0.01)\n",
1246 | "\n",
1247 | "for epoch in range(num_epochs):\n",
1248 | " print(\"========= Epoch %d of %d =========\" % (epoch+1, num_epochs))\n",
1249 | " train_loss = trainer.train(train_dataset)\n",
1250 | " valid_loss = trainer.test(valid_dataset)\n",
1251 | "\n",
1252 | " print(\"========= Results: epoch %d of %d =========\" % (epoch+1, num_epochs))\n",
1253 | " print(\"train loss: %.2f| valid loss: %.2f\\n\" % (train_loss, valid_loss) )"
1254 | ],
1255 | "execution_count": 28,
1256 | "outputs": [
1257 | {
1258 | "output_type": "stream",
1259 | "text": [
1260 | "\r 0%| | 0/208 [00:00, ?it/s]"
1261 | ],
1262 | "name": "stderr"
1263 | },
1264 | {
1265 | "output_type": "stream",
1266 | "text": [
1267 | "========= Epoch 1 of 10 =========\n"
1268 | ],
1269 | "name": "stdout"
1270 | },
1271 | {
1272 | "output_type": "stream",
1273 | "text": [
1274 | " 1%|▏ | 3/208 [00:00<00:49, 4.10it/s]"
1275 | ],
1276 | "name": "stderr"
1277 | },
1278 | {
1279 | "output_type": "stream",
1280 | "text": [
1281 | "loss: 38.27830505371094\n",
1282 | "pXTePbVjYF\n",
1283 | "[41, 61, 20, 23, 1, 29, 18, 14, 24, 24]\n",
1284 | "LuunvHIuqX\n",
1285 | "[56, 36, 38, 49, 19, 2, 23, 45, 4, 3]\n",
1286 | "bYhujZXBL\n",
1287 | "\n",
1288 | "[55, 55, 49, 39, 4, 15, 57, 23, 52, 53]\n",
1289 | "FdUCylApst\n",
1290 | "[34, 40, 36, 27, 26, 44, 53, 56, 26, 46]\n",
1291 | "FtyJoeDVk\n",
1292 | "\n",
1293 | "[34, 23, 20, 61, 6, 51, 8, 13, 34, 26]\n"
1294 | ],
1295 | "name": "stdout"
1296 | },
1297 | {
1298 | "output_type": "stream",
1299 | "text": [
1300 | " 25%|██▌ | 53/208 [00:03<00:10, 14.48it/s]"
1301 | ],
1302 | "name": "stderr"
1303 | },
1304 | {
1305 | "output_type": "stream",
1306 | "text": [
1307 | "loss: 33.30974578857422\n",
1308 | "lTsYD\n",
1309 | "ntNj\n",
1310 | "[34, 18, 44, 31, 39, 60, 21, 19, 10, 19]\n",
1311 | "gwgHosQkqc\n",
1312 | "[34, 31, 59, 19, 45, 4, 13, 63, 28, 10]\n",
1313 | "sImtUHnn\n",
1314 | "e\n",
1315 | "[6, 28, 37, 45, 27, 56, 38, 3, 9, 54]\n",
1316 | "rrgClNlKsr\n",
1317 | "[43, 49, 15, 12, 45, 1, 44, 53, 2, 63]\n",
1318 | "eXaPznhikV\n",
1319 | "[41, 42, 12, 51, 14, 1, 41, 37, 43, 15]\n"
1320 | ],
1321 | "name": "stdout"
1322 | },
1323 | {
1324 | "output_type": "stream",
1325 | "text": [
1326 | " 50%|████▉ | 103/208 [00:07<00:07, 14.90it/s]"
1327 | ],
1328 | "name": "stderr"
1329 | },
1330 | {
1331 | "output_type": "stream",
1332 | "text": [
1333 | "loss: 30.279699325561523\n",
1334 | "VdostoateO\n",
1335 | "[11, 0, 12, 14, 19, 28, 23, 62, 43, 60]\n",
1336 | "siiAilJnXc\n",
1337 | "[37, 52, 19, 37, 54, 44, 43, 48, 21, 61]\n",
1338 | "moeddnaoyw\n",
1339 | "[44, 14, 21, 37, 37, 45, 54, 50, 14, 31]\n",
1340 | "ltp-iangtI\n",
1341 | "[56, 14, 30, 9, 45, 54, 11, 15, 16, 19]\n",
1342 | "mjqratgtpr\n",
1343 | "[37, 61, 55, 49, 29, 48, 44, 35, 62, 44]\n"
1344 | ],
1345 | "name": "stdout"
1346 | },
1347 | {
1348 | "output_type": "stream",
1349 | "text": [
1350 | " 74%|███████▎ | 153/208 [00:10<00:03, 14.67it/s]"
1351 | ],
1352 | "name": "stderr"
1353 | },
1354 | {
1355 | "output_type": "stream",
1356 | "text": [
1357 | "loss: 28.56381607055664\n",
1358 | "oropeudous\n",
1359 | "[45, 14, 52, 56, 52, 49, 37, 52, 44, 14]\n",
1360 | "bltfbwikte\n",
1361 | "[56, 29, 13, 42, 38, 53, 61, 51, 14, 52]\n",
1362 | "TnDomoiibo\n",
1363 | "[19, 21, 45, 44, 44, 53, 61, 24, 56, 59]\n",
1364 | "niisehoLtL\n",
1365 | "[38, 54, 19, 60, 50, 49, 39, 6, 23, 52]\n",
1366 | "cstoeGebec\n",
1367 | "[33, 54, 23, 52, 29, 13, 52, 56, 52, 45]\n"
1368 | ],
1369 | "name": "stdout"
1370 | },
1371 | {
1372 | "output_type": "stream",
1373 | "text": [
1374 | " 98%|█████████▊| 203/208 [00:13<00:00, 14.73it/s]"
1375 | ],
1376 | "name": "stderr"
1377 | },
1378 | {
1379 | "output_type": "stream",
1380 | "text": [
1381 | "loss: 26.615825653076172\n",
1382 | "-ibBiNplii\n",
1383 | "[25, 61, 60, 23, 61, 60, 56, 49, 61, 56]\n",
1384 | "eKteaeraei\n",
1385 | "[8, 44, 23, 50, 21, 50, 37, 52, 56, 59]\n",
1386 | "mafkfibjta\n",
1387 | "[20, 29, 35, 57, 20, 52, 56, 52, 62, 29]\n",
1388 | "unJhevRlcu\n",
1389 | "[42, 21, 48, 9, 61, 40, 50, 14, 45, 39]\n",
1390 | "uoryatidol\n",
1391 | "[34, 44, 14, 61, 29, 23, 61, 48, 28, 58]\n"
1392 | ],
1393 | "name": "stdout"
1394 | },
1395 | {
1396 | "output_type": "stream",
1397 | "text": [
1398 | "100%|██████████| 208/208 [00:13<00:00, 14.91it/s]\n"
1399 | ],
1400 | "name": "stderr"
1401 | },
1402 | {
1403 | "output_type": "stream",
1404 | "text": [
1405 | "loss: 26.30190658569336\n",
1406 | "wusstetiNr\n",
1407 | "[25, 39, 60, 32, 23, 52, 18, 59, 24, 45]\n"
1408 | ],
1409 | "name": "stdout"
1410 | },
1411 | {
1412 | "output_type": "stream",
1413 | "text": [
1414 | "\r 0%| | 0/208 [00:00, ?it/s]"
1415 | ],
1416 | "name": "stderr"
1417 | },
1418 | {
1419 | "output_type": "stream",
1420 | "text": [
1421 | "========= Results: epoch 1 of 10 =========\n",
1422 | "train loss: 30.75| valid loss: 26.34\n",
1423 | "\n",
1424 | "========= Epoch 2 of 10 =========\n"
1425 | ],
1426 | "name": "stdout"
1427 | },
1428 | {
1429 | "output_type": "stream",
1430 | "text": [
1431 | " 1%|▏ | 3/208 [00:00<00:44, 4.58it/s]"
1432 | ],
1433 | "name": "stderr"
1434 | },
1435 | {
1436 | "output_type": "stream",
1437 | "text": [
1438 | "loss: 26.122982025146484\n",
1439 | "undaiqirii\n",
1440 | "[42, 21, 48, 14, 59, 14, 59, 14, 59, 19]\n",
1441 | "rtpsernaim\n",
1442 | "[56, 14, 61, 32, 13, 42, 21, 48, 59, 37]\n",
1443 | "oedsKinide\n",
1444 | "[1, 52, 35, 54, 16, 61, 21, 61, 48, 50]\n",
1445 | "cydeneison\n",
1446 | "[48, 52, 40, 50, 21, 52, 19, 32, 59, 21]\n",
1447 | "dusttMlyet\n",
1448 | "[31, 39, 60, 23, 45, 63, 43, 14, 52, 23]\n"
1449 | ],
1450 | "name": "stdout"
1451 | },
1452 | {
1453 | "output_type": "stream",
1454 | "text": [
1455 | " 25%|██▌ | 53/208 [00:03<00:10, 14.94it/s]"
1456 | ],
1457 | "name": "stderr"
1458 | },
1459 | {
1460 | "output_type": "stream",
1461 | "text": [
1462 | "loss: 25.615436553955078\n",
1463 | "bedisYmasu\n",
1464 | "[37, 50, 37, 61, 60, 32, 33, 29, 45, 39]\n",
1465 | "hiSncratrb\n",
1466 | "[9, 59, 47, 21, 11, 49, 29, 23, 35, 53]\n",
1467 | "pricuuriss\n",
1468 | "[56, 9, 19, 60, 34, 39, 37, 19, 60, 32]\n",
1469 | "Loiptikenb\n",
1470 | "[12, 52, 54, 3, 23, 61, 48, 50, 21, 27]\n",
1471 | "carcomaepo\n",
1472 | "[11, 59, 21, 37, 52, 60, 23, 52, 56, 59]\n"
1473 | ],
1474 | "name": "stdout"
1475 | },
1476 | {
1477 | "output_type": "stream",
1478 | "text": [
1479 | " 50%|████▉ | 103/208 [00:06<00:06, 15.11it/s]"
1480 | ],
1481 | "name": "stderr"
1482 | },
1483 | {
1484 | "output_type": "stream",
1485 | "text": [
1486 | "loss: 24.506874084472656\n",
1487 | "untirtinra\n",
1488 | "[42, 21, 48, 19, 21, 48, 61, 11, 9, 29]\n",
1489 | "macdestior\n",
1490 | "[20, 29, 35, 48, 50, 43, 48, 19, 45, 21]\n",
1491 | "dptodingis\n",
1492 | "[37, 3, 23, 52, 48, 19, 21, 22, 61, 60]\n",
1493 | "pdliseenno\n",
1494 | "[56, 44, 53, 61, 60, 32, 50, 43, 21, 52]\n",
1495 | "urLlhsumil\n",
1496 | "[42, 21, 61, 48, 9, 31, 39, 37, 61, 58]\n"
1497 | ],
1498 | "name": "stdout"
1499 | },
1500 | {
1501 | "output_type": "stream",
1502 | "text": [
1503 | " 74%|███████▎ | 153/208 [00:10<00:03, 14.25it/s]"
1504 | ],
1505 | "name": "stderr"
1506 | },
1507 | {
1508 | "output_type": "stream",
1509 | "text": [
1510 | "loss: 24.405460357666016\n",
1511 | "inthtemlis\n",
1512 | "[42, 21, 48, 49, 45, 50, 37, 17, 61, 60]\n",
1513 | "rterideran\n",
1514 | "[14, 8, 52, 37, 61, 48, 50, 14, 29, 21]\n",
1515 | "ipimufferu\n",
1516 | "[19, 12, 59, 37, 61, 58, 57, 52, 14, 61]\n",
1517 | "pracansing\n",
1518 | "[56, 14, 52, 34, 54, 43, 32, 19, 21, 48]\n",
1519 | "sermyssuae\n",
1520 | "[56, 50, 43, 37, 61, 60, 31, 39, 14, 52]\n"
1521 | ],
1522 | "name": "stdout"
1523 | },
1524 | {
1525 | "output_type": "stream",
1526 | "text": [
1527 | " 98%|█████████▊| 203/208 [00:13<00:00, 14.90it/s]"
1528 | ],
1529 | "name": "stderr"
1530 | },
1531 | {
1532 | "output_type": "stream",
1533 | "text": [
1534 | "loss: 24.571157455444336\n",
1535 | "diniainiWs\n",
1536 | "[48, 61, 56, 61, 29, 35, 48, 61, 60, 32]\n",
1537 | "rydepreken\n",
1538 | "[14, 52, 48, 52, 56, 14, 52, 22, 50, 21]\n",
1539 | "catheallon\n",
1540 | "[11, 29, 23, 9, 59, 29, 35, 53, 52, 21]\n",
1541 | "dusmotiona\n",
1542 | "[31, 39, 60, 23, 59, 23, 19, 45, 21, 54]\n",
1543 | "teagenybaa\n",
1544 | "[56, 59, 29, 26, 50, 14, 52, 56, 29, 19]\n"
1545 | ],
1546 | "name": "stdout"
1547 | },
1548 | {
1549 | "output_type": "stream",
1550 | "text": [
1551 | "100%|██████████| 208/208 [00:13<00:00, 15.03it/s]\n"
1552 | ],
1553 | "name": "stderr"
1554 | },
1555 | {
1556 | "output_type": "stream",
1557 | "text": [
1558 | "loss: 24.482282638549805\n",
1559 | "parsealogi\n",
1560 | "[56, 50, 21, 23, 52, 29, 53, 52, 22, 61]\n"
1561 | ],
1562 | "name": "stdout"
1563 | },
1564 | {
1565 | "output_type": "stream",
1566 | "text": [
1567 | "\r 0%| | 0/208 [00:00, ?it/s]"
1568 | ],
1569 | "name": "stderr"
1570 | },
1571 | {
1572 | "output_type": "stream",
1573 | "text": [
1574 | "========= Results: epoch 2 of 10 =========\n",
1575 | "train loss: 25.03| valid loss: 24.38\n",
1576 | "\n",
1577 | "========= Epoch 3 of 10 =========\n"
1578 | ],
1579 | "name": "stdout"
1580 | },
1581 | {
1582 | "output_type": "stream",
1583 | "text": [
1584 | " 1%|▏ | 3/208 [00:00<00:43, 4.69it/s]"
1585 | ],
1586 | "name": "stderr"
1587 | },
1588 | {
1589 | "output_type": "stream",
1590 | "text": [
1591 | "loss: 24.47772216796875\n",
1592 | "Didanidive\n",
1593 | "[12, 19, 48, 59, 37, 61, 48, 61, 40, 50]\n",
1594 | "ledspEulli\n",
1595 | "[56, 50, 21, 60, 32, 39, 39, 3, 53, 61]\n",
1596 | "setontetil\n",
1597 | "[20, 59, 23, 59, 21, 48, 50, 23, 61, 21]\n",
1598 | "croosxaunc\n",
1599 | "[56, 14, 45, 39, 60, 23, 59, 42, 21, 11]\n",
1600 | "phoousyycf\n",
1601 | "[56, 9, 52, 45, 39, 60, 9, 52, 11, 62]\n"
1602 | ],
1603 | "name": "stdout"
1604 | },
1605 | {
1606 | "output_type": "stream",
1607 | "text": [
1608 | " 25%|██▌ | 53/208 [00:03<00:10, 14.75it/s]"
1609 | ],
1610 | "name": "stderr"
1611 | },
1612 | {
1613 | "output_type": "stream",
1614 | "text": [
1615 | "loss: 23.98973274230957\n",
1616 | "megleraldh\n",
1617 | "[20, 52, 22, 53, 52, 14, 29, 35, 48, 9]\n",
1618 | "unrphygnRt\n",
1619 | "[42, 21, 43, 32, 9, 52, 22, 53, 61, 58]\n",
1620 | "urtiatudic\n",
1621 | "[42, 21, 23, 61, 29, 23, 59, 37, 61, 11]\n",
1622 | "aochantere\n",
1623 | "[37, 52, 11, 9, 59, 21, 48, 50, 21, 42]\n",
1624 | "apkhyonvTn\n",
1625 | "[54, 3, 23, 9, 52, 59, 21, 40, 50, 53]\n"
1626 | ],
1627 | "name": "stdout"
1628 | },
1629 | {
1630 | "output_type": "stream",
1631 | "text": [
1632 | " 50%|████▉ | 103/208 [00:07<00:07, 14.89it/s]"
1633 | ],
1634 | "name": "stderr"
1635 | },
1636 | {
1637 | "output_type": "stream",
1638 | "text": [
1639 | "loss: 23.897340774536133\n",
1640 | "shybinponm\n",
1641 | "[60, 33, 52, 48, 61, 21, 56, 52, 21, 32]\n",
1642 | "sulneraaer\n",
1643 | "[31, 39, 35, 53, 50, 14, 29, 23, 50, 14]\n",
1644 | "retomegero\n",
1645 | "[14, 52, 23, 50, 14, 52, 22, 50, 14, 59]\n",
1646 | "peiardhema\n",
1647 | "[56, 49, 61, 29, 21, 48, 9, 50, 37, 29]\n",
1648 | "tigintinte\n",
1649 | "[56, 61, 40, 19, 21, 23, 61, 21, 48, 50]\n"
1650 | ],
1651 | "name": "stdout"
1652 | },
1653 | {
1654 | "output_type": "stream",
1655 | "text": [
1656 | " 74%|███████▎ | 153/208 [00:10<00:03, 14.40it/s]"
1657 | ],
1658 | "name": "stderr"
1659 | },
1660 | {
1661 | "output_type": "stream",
1662 | "text": [
1663 | "loss: 23.973764419555664\n",
1664 | "ctotatovat\n",
1665 | "[11, 23, 59, 37, 29, 23, 45, 40, 29, 23]\n",
1666 | "Bigindoric\n",
1667 | "[25, 19, 48, 19, 21, 48, 52, 37, 61, 11]\n",
1668 | "prombejcer\n",
1669 | "[56, 14, 52, 37, 16, 50, 43, 32, 59, 21]\n",
1670 | "diwuedrase\n",
1671 | "[20, 59, 37, 56, 52, 44, 14, 29, 60, 50]\n",
1672 | "entamitppa\n",
1673 | "[42, 21, 23, 29, 37, 19, 48, 3, 56, 29]\n"
1674 | ],
1675 | "name": "stdout"
1676 | },
1677 | {
1678 | "output_type": "stream",
1679 | "text": [
1680 | " 98%|█████████▊| 203/208 [00:13<00:00, 14.87it/s]"
1681 | ],
1682 | "name": "stderr"
1683 | },
1684 | {
1685 | "output_type": "stream",
1686 | "text": [
1687 | "loss: 23.922351837158203\n",
1688 | "sfolycannu\n",
1689 | "[54, 58, 59, 53, 52, 11, 29, 21, 48, 50]\n",
1690 | "Barantiang\n",
1691 | "[20, 52, 37, 29, 21, 23, 61, 29, 21, 22]\n",
1692 | "unovemaler\n",
1693 | "[42, 21, 52, 40, 50, 37, 29, 23, 50, 14]\n",
1694 | "lonquactid\n",
1695 | "[20, 59, 21, 13, 36, 29, 60, 23, 61, 48]\n",
1696 | "testicarto\n",
1697 | "[56, 52, 60, 23, 61, 11, 29, 21, 11, 59]\n"
1698 | ],
1699 | "name": "stdout"
1700 | },
1701 | {
1702 | "output_type": "stream",
1703 | "text": [
1704 | "100%|██████████| 208/208 [00:14<00:00, 14.80it/s]\n"
1705 | ],
1706 | "name": "stderr"
1707 | },
1708 | {
1709 | "output_type": "stream",
1710 | "text": [
1711 | "loss: 24.101062774658203\n",
1712 | "porgupettm\n",
1713 | "[56, 59, 21, 22, 39, 56, 50, 23, 23, 15]\n"
1714 | ],
1715 | "name": "stdout"
1716 | },
1717 | {
1718 | "output_type": "stream",
1719 | "text": [
1720 | "\r 0%| | 0/208 [00:00, ?it/s]"
1721 | ],
1722 | "name": "stderr"
1723 | },
1724 | {
1725 | "output_type": "stream",
1726 | "text": [
1727 | "========= Results: epoch 3 of 10 =========\n",
1728 | "train loss: 24.04| valid loss: 23.87\n",
1729 | "\n",
1730 | "========= Epoch 4 of 10 =========\n"
1731 | ],
1732 | "name": "stdout"
1733 | },
1734 | {
1735 | "output_type": "stream",
1736 | "text": [
1737 | " 1%|▏ | 3/208 [00:00<00:48, 4.20it/s]"
1738 | ],
1739 | "name": "stderr"
1740 | },
1741 | {
1742 | "output_type": "stream",
1743 | "text": [
1744 | "loss: 23.310888290405273\n",
1745 | "sitelarves\n",
1746 | "[37, 61, 48, 50, 35, 29, 43, 40, 50, 14]\n",
1747 | "froscerseo\n",
1748 | "[25, 49, 54, 60, 32, 50, 43, 60, 32, 59]\n",
1749 | "docegellor\n",
1750 | "[20, 19, 48, 52, 22, 50, 35, 53, 50, 14]\n",
1751 | "slrAsancol\n",
1752 | "[60, 23, 49, 54, 48, 29, 21, 11, 59, 53]\n",
1753 | "oantassush\n",
1754 | "[20, 29, 21, 23, 29, 60, 31, 39, 60, 9]\n"
1755 | ],
1756 | "name": "stdout"
1757 | },
1758 | {
1759 | "output_type": "stream",
1760 | "text": [
1761 | " 25%|██▌ | 53/208 [00:03<00:10, 14.20it/s]"
1762 | ],
1763 | "name": "stderr"
1764 | },
1765 | {
1766 | "output_type": "stream",
1767 | "text": [
1768 | "loss: 23.963918685913086\n",
1769 | "wymanecean\n",
1770 | "[34, 52, 37, 29, 48, 52, 23, 61, 29, 21]\n",
1771 | "Chuhcstele\n",
1772 | "[12, 9, 52, 33, 52, 60, 23, 50, 14, 52]\n",
1773 | "rewmencuPm\n",
1774 | "[37, 50, 43, 37, 50, 21, 11, 39, 15, 37]\n",
1775 | "uneatwoGui\n",
1776 | "[42, 21, 52, 29, 23, 49, 54, 13, 36, 19]\n",
1777 | "burslemere\n",
1778 | "[20, 39, 43, 60, 53, 52, 37, 50, 14, 52]\n"
1779 | ],
1780 | "name": "stdout"
1781 | },
1782 | {
1783 | "output_type": "stream",
1784 | "text": [
1785 | " 50%|████▉ | 103/208 [00:07<00:07, 14.88it/s]"
1786 | ],
1787 | "name": "stderr"
1788 | },
1789 | {
1790 | "output_type": "stream",
1791 | "text": [
1792 | "loss: 23.50936508178711\n",
1793 | "manerbened\n",
1794 | "[20, 29, 21, 50, 43, 16, 59, 37, 50, 44]\n",
1795 | "agdricalos\n",
1796 | "[54, 26, 22, 49, 61, 11, 29, 53, 52, 60]\n",
1797 | "utcantedra\n",
1798 | "[42, 21, 11, 59, 21, 23, 52, 22, 49, 29]\n",
1799 | "honctermis\n",
1800 | "[20, 59, 21, 11, 23, 50, 43, 37, 19, 60]\n",
1801 | "rymichagat\n",
1802 | "[14, 52, 37, 61, 11, 9, 29, 22, 50, 23]\n"
1803 | ],
1804 | "name": "stdout"
1805 | },
1806 | {
1807 | "output_type": "stream",
1808 | "text": [
1809 | " 74%|███████▎ | 153/208 [00:10<00:03, 14.39it/s]"
1810 | ],
1811 | "name": "stderr"
1812 | },
1813 | {
1814 | "output_type": "stream",
1815 | "text": [
1816 | "loss: 23.392898559570312\n",
1817 | "rysgastang\n",
1818 | "[14, 52, 60, 17, 29, 60, 23, 29, 21, 22]\n",
1819 | "aswcereeri\n",
1820 | "[54, 60, 61, 48, 50, 14, 52, 50, 14, 61]\n",
1821 | "tawwleunol\n",
1822 | "[56, 29, 60, 32, 53, 52, 27, 48, 29, 35]\n",
1823 | "mepcormian\n",
1824 | "[20, 52, 3, 56, 59, 43, 32, 61, 29, 21]\n",
1825 | "ctatiskati\n",
1826 | "[11, 23, 29, 23, 61, 60, 32, 29, 23, 61]\n"
1827 | ],
1828 | "name": "stdout"
1829 | },
1830 | {
1831 | "output_type": "stream",
1832 | "text": [
1833 | " 98%|█████████▊| 203/208 [00:13<00:00, 14.38it/s]"
1834 | ],
1835 | "name": "stderr"
1836 | },
1837 | {
1838 | "output_type": "stream",
1839 | "text": [
1840 | "loss: 23.561634063720703\n",
1841 | "lmnoloulad\n",
1842 | "[42, 15, 37, 59, 14, 45, 39, 35, 29, 48]\n",
1843 | "fueiyloesi\n",
1844 | "[31, 39, 43, 51, 52, 22, 52, 54, 60, 61]\n",
1845 | "chertratra\n",
1846 | "[11, 9, 50, 43, 23, 14, 29, 23, 49, 54]\n",
1847 | "hyacrepage\n",
1848 | "[33, 52, 29, 11, 14, 52, 56, 29, 22, 50]\n",
1849 | "opphertetn\n",
1850 | "[54, 3, 3, 9, 52, 21, 23, 61, 23, 21]\n"
1851 | ],
1852 | "name": "stdout"
1853 | },
1854 | {
1855 | "output_type": "stream",
1856 | "text": [
1857 | "100%|██████████| 208/208 [00:14<00:00, 14.78it/s]\n"
1858 | ],
1859 | "name": "stderr"
1860 | },
1861 | {
1862 | "output_type": "stream",
1863 | "text": [
1864 | "loss: 23.406665802001953\n",
1865 | "antetepyry\n",
1866 | "[42, 21, 48, 52, 11, 52, 3, 52, 14, 52]\n"
1867 | ],
1868 | "name": "stdout"
1869 | },
1870 | {
1871 | "output_type": "stream",
1872 | "text": [
1873 | "\r 0%| | 0/208 [00:00, ?it/s]"
1874 | ],
1875 | "name": "stderr"
1876 | },
1877 | {
1878 | "output_type": "stream",
1879 | "text": [
1880 | "========= Results: epoch 4 of 10 =========\n",
1881 | "train loss: 23.72| valid loss: 23.66\n",
1882 | "\n",
1883 | "========= Epoch 5 of 10 =========\n"
1884 | ],
1885 | "name": "stdout"
1886 | },
1887 | {
1888 | "output_type": "stream",
1889 | "text": [
1890 | " 1%|▏ | 3/208 [00:00<00:44, 4.62it/s]"
1891 | ],
1892 | "name": "stderr"
1893 | },
1894 | {
1895 | "output_type": "stream",
1896 | "text": [
1897 | "loss: 23.822376251220703\n",
1898 | "Tuwurarixa\n",
1899 | "[20, 59, 37, 59, 37, 29, 43, 19, 48, 29]\n",
1900 | "neritelat-\n",
1901 | "[20, 50, 43, 19, 48, 50, 35, 29, 23, 29]\n",
1902 | "Tiantfwhlo\n",
1903 | "[20, 19, 29, 21, 11, 57, 12, 9, 53, 52]\n",
1904 | "Malloeshoc\n",
1905 | "[20, 29, 35, 53, 52, 54, 60, 9, 52, 11]\n",
1906 | "dolalasten\n",
1907 | "[20, 59, 14, 52, 53, 52, 60, 23, 50, 21]\n"
1908 | ],
1909 | "name": "stdout"
1910 | },
1911 | {
1912 | "output_type": "stream",
1913 | "text": [
1914 | " 25%|██▌ | 53/208 [00:03<00:10, 14.70it/s]"
1915 | ],
1916 | "name": "stderr"
1917 | },
1918 | {
1919 | "output_type": "stream",
1920 | "text": [
1921 | "loss: 23.547645568847656\n",
1922 | "Phyfloquia\n",
1923 | "[12, 9, 52, 22, 53, 52, 13, 36, 19, 29]\n",
1924 | "ectantiTat\n",
1925 | "[54, 11, 23, 59, 21, 23, 61, 48, 29, 23]\n",
1926 | "odlustannc\n",
1927 | "[54, 27, 14, 52, 60, 23, 29, 21, 21, 11]\n",
1928 | "acaryreidl\n",
1929 | "[54, 11, 59, 14, 52, 37, 61, 21, 22, 53]\n",
1930 | "ratcethell\n",
1931 | "[14, 52, 60, 23, 50, 23, 9, 52, 35, 53]\n"
1932 | ],
1933 | "name": "stdout"
1934 | },
1935 | {
1936 | "output_type": "stream",
1937 | "text": [
1938 | " 50%|████▉ | 103/208 [00:07<00:07, 14.27it/s]"
1939 | ],
1940 | "name": "stderr"
1941 | },
1942 | {
1943 | "output_type": "stream",
1944 | "text": [
1945 | "loss: 23.812715530395508\n",
1946 | "trLceungop\n",
1947 | "[56, 14, 61, 11, 52, 42, 21, 22, 59, 3]\n",
1948 | "aperkishys\n",
1949 | "[54, 3, 50, 43, 57, 19, 60, 9, 52, 60]\n",
1950 | "septhwoxig\n",
1951 | "[20, 59, 3, 23, 9, 0, 59, 37, 61, 26]\n",
1952 | "zorantsore\n",
1953 | "[20, 59, 14, 29, 21, 60, 32, 59, 43, 50]\n",
1954 | "dofleniaba\n",
1955 | "[20, 52, 62, 53, 52, 37, 19, 29, 38, 59]\n"
1956 | ],
1957 | "name": "stdout"
1958 | },
1959 | {
1960 | "output_type": "stream",
1961 | "text": [
1962 | " 74%|███████▎ | 153/208 [00:10<00:03, 14.17it/s]"
1963 | ],
1964 | "name": "stderr"
1965 | },
1966 | {
1967 | "output_type": "stream",
1968 | "text": [
1969 | "loss: 23.58541488647461\n",
1970 | "quiablarai\n",
1971 | "[13, 36, 19, 29, 38, 53, 29, 43, 29, 7]\n",
1972 | "ranteiishu\n",
1973 | "[31, 42, 21, 23, 50, 35, 19, 60, 9, 59]\n",
1974 | "hidlopenad\n",
1975 | "[33, 52, 44, 53, 52, 56, 50, 21, 54, 44]\n",
1976 | "acovagungn\n",
1977 | "[54, 11, 59, 40, 29, 28, 42, 21, 22, 53]\n",
1978 | "poplyissou\n",
1979 | "[56, 59, 3, 53, 52, 19, 60, 32, 45, 39]\n"
1980 | ],
1981 | "name": "stdout"
1982 | },
1983 | {
1984 | "output_type": "stream",
1985 | "text": [
1986 | " 98%|█████████▊| 203/208 [00:13<00:00, 14.30it/s]"
1987 | ],
1988 | "name": "stderr"
1989 | },
1990 | {
1991 | "output_type": "stream",
1992 | "text": [
1993 | "loss: 23.362699508666992\n",
1994 | "eutigxisth\n",
1995 | "[54, 27, 23, 61, 26, 37, 19, 60, 23, 9]\n",
1996 | "wivyrocyll\n",
1997 | "[20, 61, 40, 50, 14, 29, 11, 7, 35, 35]\n",
1998 | "purrlescer\n",
1999 | "[56, 39, 43, 22, 53, 52, 60, 23, 50, 43]\n",
2000 | "sweridater\n",
2001 | "[31, 0, 59, 43, 19, 48, 29, 23, 50, 43]\n",
2002 | "herystindy\n",
2003 | "[33, 50, 14, 52, 60, 23, 61, 21, 48, 52]\n"
2004 | ],
2005 | "name": "stdout"
2006 | },
2007 | {
2008 | "output_type": "stream",
2009 | "text": [
2010 | "100%|██████████| 208/208 [00:14<00:00, 14.79it/s]\n"
2011 | ],
2012 | "name": "stderr"
2013 | },
2014 | {
2015 | "output_type": "stream",
2016 | "text": [
2017 | "loss: 23.546817779541016\n",
2018 | "susmleptya\n",
2019 | "[31, 39, 60, 32, 53, 52, 3, 23, 52, 54]\n"
2020 | ],
2021 | "name": "stdout"
2022 | },
2023 | {
2024 | "output_type": "stream",
2025 | "text": [
2026 | "\r 0%| | 0/208 [00:00, ?it/s]"
2027 | ],
2028 | "name": "stderr"
2029 | },
2030 | {
2031 | "output_type": "stream",
2032 | "text": [
2033 | "========= Results: epoch 5 of 10 =========\n",
2034 | "train loss: 23.55| valid loss: 23.53\n",
2035 | "\n",
2036 | "========= Epoch 6 of 10 =========\n"
2037 | ],
2038 | "name": "stdout"
2039 | },
2040 | {
2041 | "output_type": "stream",
2042 | "text": [
2043 | " 1%|▏ | 3/208 [00:00<00:46, 4.41it/s]"
2044 | ],
2045 | "name": "stderr"
2046 | },
2047 | {
2048 | "output_type": "stream",
2049 | "text": [
2050 | "loss: 23.335289001464844\n",
2051 | "iiayischyr\n",
2052 | "[41, 19, 29, 52, 19, 60, 11, 9, 52, 14]\n",
2053 | "tesishepry\n",
2054 | "[20, 54, 60, 19, 60, 9, 52, 56, 14, 52]\n",
2055 | "upryrechni\n",
2056 | "[42, 56, 14, 52, 14, 52, 11, 9, 37, 19]\n",
2057 | "wonerpgaza\n",
2058 | "[20, 59, 37, 50, 43, 3, 17, 29, 48, 29]\n",
2059 | "untumunamb\n",
2060 | "[42, 21, 23, 27, 18, 42, 21, 29, 15, 16]\n"
2061 | ],
2062 | "name": "stdout"
2063 | },
2064 | {
2065 | "output_type": "stream",
2066 | "text": [
2067 | " 25%|██▌ | 53/208 [00:03<00:10, 14.13it/s]"
2068 | ],
2069 | "name": "stderr"
2070 | },
2071 | {
2072 | "output_type": "stream",
2073 | "text": [
2074 | "loss: 23.553653717041016\n",
2075 | "snesichils\n",
2076 | "[31, 53, 52, 60, 19, 23, 9, 7, 35, 37]\n",
2077 | "shilispern\n",
2078 | "[60, 9, 7, 35, 19, 60, 32, 50, 43, 37]\n",
2079 | "suwestiorv\n",
2080 | "[31, 27, 37, 52, 60, 23, 61, 59, 43, 40]\n",
2081 | "atolnetull\n",
2082 | "[29, 23, 59, 35, 53, 52, 23, 39, 35, 53]\n",
2083 | "coregueten\n",
2084 | "[20, 59, 14, 52, 22, 36, 19, 48, 50, 21]\n"
2085 | ],
2086 | "name": "stdout"
2087 | },
2088 | {
2089 | "output_type": "stream",
2090 | "text": [
2091 | " 50%|████▉ | 103/208 [00:07<00:07, 14.26it/s]"
2092 | ],
2093 | "name": "stderr"
2094 | },
2095 | {
2096 | "output_type": "stream",
2097 | "text": [
2098 | "loss: 23.50783920288086\n",
2099 | "psouscater\n",
2100 | "[56, 14, 45, 39, 60, 23, 29, 23, 50, 14]\n",
2101 | "soriirousq\n",
2102 | "[20, 59, 37, 19, 47, 14, 45, 39, 60, 13]\n",
2103 | "lalotiosat\n",
2104 | "[34, 29, 35, 29, 23, 61, 59, 37, 52, 23]\n",
2105 | "chooguaxti\n",
2106 | "[11, 9, 59, 59, 26, 36, 29, 21, 23, 61]\n",
2107 | "Caubeliric\n",
2108 | "[20, 29, 27, 37, 29, 35, 19, 14, 61, 41]\n"
2109 | ],
2110 | "name": "stdout"
2111 | },
2112 | {
2113 | "output_type": "stream",
2114 | "text": [
2115 | " 74%|███████▎ | 153/208 [00:10<00:03, 14.69it/s]"
2116 | ],
2117 | "name": "stderr"
2118 | },
2119 | {
2120 | "output_type": "stream",
2121 | "text": [
2122 | "loss: 23.355899810791016\n",
2123 | "mutedpundi\n",
2124 | "[20, 27, 23, 50, 44, 41, 42, 21, 48, 19]\n",
2125 | "unresepent\n",
2126 | "[42, 21, 14, 52, 60, 52, 3, 50, 21, 48]\n",
2127 | "potedlebro\n",
2128 | "[56, 52, 23, 50, 44, 53, 52, 55, 49, 59]\n",
2129 | "mesconerad\n",
2130 | "[20, 19, 60, 23, 61, 37, 59, 43, 29, 22]\n",
2131 | "prangecrys\n",
2132 | "[56, 14, 29, 21, 22, 52, 11, 14, 52, 37]\n"
2133 | ],
2134 | "name": "stdout"
2135 | },
2136 | {
2137 | "output_type": "stream",
2138 | "text": [
2139 | " 98%|█████████▊| 203/208 [00:13<00:00, 14.34it/s]"
2140 | ],
2141 | "name": "stderr"
2142 | },
2143 | {
2144 | "output_type": "stream",
2145 | "text": [
2146 | "loss: 23.536277770996094\n",
2147 | "Antrianges\n",
2148 | "[42, 21, 23, 49, 19, 29, 21, 22, 52, 60]\n",
2149 | "dosmidoner\n",
2150 | "[20, 52, 60, 32, 19, 48, 50, 21, 54, 43]\n",
2151 | "tryloblegi\n",
2152 | "[25, 49, 52, 53, 52, 55, 49, 54, 11, 19]\n",
2153 | "slyopowert\n",
2154 | "[31, 53, 52, 54, 3, 52, 0, 50, 43, 23]\n",
2155 | "lamorlossw\n",
2156 | "[20, 52, 37, 59, 43, 14, 52, 60, 32, 0]\n"
2157 | ],
2158 | "name": "stdout"
2159 | },
2160 | {
2161 | "output_type": "stream",
2162 | "text": [
2163 | "100%|██████████| 208/208 [00:14<00:00, 14.80it/s]\n"
2164 | ],
2165 | "name": "stderr"
2166 | },
2167 | {
2168 | "output_type": "stream",
2169 | "text": [
2170 | "loss: 23.495555877685547\n",
2171 | "screjurmic\n",
2172 | "[31, 11, 14, 52, 10, 27, 14, 37, 19, 48]\n"
2173 | ],
2174 | "name": "stdout"
2175 | },
2176 | {
2177 | "output_type": "stream",
2178 | "text": [
2179 | "\r 0%| | 0/208 [00:00, ?it/s]"
2180 | ],
2181 | "name": "stderr"
2182 | },
2183 | {
2184 | "output_type": "stream",
2185 | "text": [
2186 | "========= Results: epoch 6 of 10 =========\n",
2187 | "train loss: 23.44| valid loss: 23.43\n",
2188 | "\n",
2189 | "========= Epoch 7 of 10 =========\n"
2190 | ],
2191 | "name": "stdout"
2192 | },
2193 | {
2194 | "output_type": "stream",
2195 | "text": [
2196 | " 1%|▏ | 3/208 [00:00<00:44, 4.58it/s]"
2197 | ],
2198 | "name": "stderr"
2199 | },
2200 | {
2201 | "output_type": "stream",
2202 | "text": [
2203 | "loss: 23.401981353759766\n",
2204 | "catrourequ\n",
2205 | "[20, 29, 23, 49, 54, 27, 14, 52, 13, 36]\n",
2206 | "Exalistife\n",
2207 | "[42, 21, 29, 35, 19, 60, 23, 61, 58, 50]\n",
2208 | "ivenitiora\n",
2209 | "[54, 40, 50, 21, 19, 23, 61, 59, 37, 29]\n",
2210 | "micaramaJi\n",
2211 | "[20, 61, 11, 29, 43, 29, 37, 29, 58, 19]\n",
2212 | "bydionatea\n",
2213 | "[51, 50, 44, 61, 59, 21, 19, 48, 52, 54]\n"
2214 | ],
2215 | "name": "stdout"
2216 | },
2217 | {
2218 | "output_type": "stream",
2219 | "text": [
2220 | " 25%|██▌ | 53/208 [00:03<00:10, 14.46it/s]"
2221 | ],
2222 | "name": "stderr"
2223 | },
2224 | {
2225 | "output_type": "stream",
2226 | "text": [
2227 | "loss: 23.47461700439453\n",
2228 | "cophoninyw\n",
2229 | "[11, 59, 3, 9, 59, 37, 19, 48, 52, 0]\n",
2230 | "plergidedi\n",
2231 | "[56, 14, 52, 21, 22, 19, 48, 50, 44, 19]\n",
2232 | "demorcicon\n",
2233 | "[20, 52, 37, 59, 43, 23, 61, 11, 59, 37]\n",
2234 | "sephontedo\n",
2235 | "[31, 52, 60, 9, 59, 21, 23, 50, 44, 59]\n",
2236 | "chenkethio\n",
2237 | "[11, 33, 50, 21, 57, 50, 23, 9, 61, 29]\n"
2238 | ],
2239 | "name": "stdout"
2240 | },
2241 | {
2242 | "output_type": "stream",
2243 | "text": [
2244 | " 50%|████▉ | 103/208 [00:07<00:07, 14.96it/s]"
2245 | ],
2246 | "name": "stderr"
2247 | },
2248 | {
2249 | "output_type": "stream",
2250 | "text": [
2251 | "loss: 22.983810424804688\n",
2252 | "spuclyytoa\n",
2253 | "[31, 56, 52, 22, 53, 52, 52, 23, 59, 59]\n",
2254 | "ingompeliz\n",
2255 | "[42, 21, 22, 59, 15, 56, 50, 35, 19, 48]\n",
2256 | "rodderlive\n",
2257 | "[49, 54, 44, 22, 50, 43, 53, 61, 40, 50]\n",
2258 | "molintorct\n",
2259 | "[20, 54, 35, 19, 21, 23, 59, 43, 11, 23]\n",
2260 | "chonelanis\n",
2261 | "[12, 9, 61, 53, 52, 53, 52, 37, 19, 48]\n"
2262 | ],
2263 | "name": "stdout"
2264 | },
2265 | {
2266 | "output_type": "stream",
2267 | "text": [
2268 | " 74%|███████▎ | 153/208 [00:10<00:03, 14.76it/s]"
2269 | ],
2270 | "name": "stderr"
2271 | },
2272 | {
2273 | "output_type": "stream",
2274 | "text": [
2275 | "loss: 23.47952651977539\n",
2276 | "luloitmena\n",
2277 | "[20, 7, 35, 45, 19, 60, 18, 50, 21, 29]\n",
2278 | "dedaificke\n",
2279 | "[20, 52, 37, 29, 19, 58, 61, 11, 57, 50]\n",
2280 | "anititivea\n",
2281 | "[42, 21, 61, 48, 19, 48, 52, 40, 50, 29]\n",
2282 | "cuslictfun\n",
2283 | "[11, 39, 32, 53, 61, 11, 23, 41, 42, 21]\n",
2284 | "helatiplud\n",
2285 | "[20, 54, 35, 29, 23, 61, 3, 53, 52, 37]\n"
2286 | ],
2287 | "name": "stdout"
2288 | },
2289 | {
2290 | "output_type": "stream",
2291 | "text": [
2292 | " 98%|█████████▊| 203/208 [00:13<00:00, 14.76it/s]"
2293 | ],
2294 | "name": "stderr"
2295 | },
2296 | {
2297 | "output_type": "stream",
2298 | "text": [
2299 | "loss: 23.140419006347656\n",
2300 | "bralomagei\n",
2301 | "[55, 49, 54, 35, 45, 37, 29, 1, 52, 19]\n",
2302 | "Erydnyrhic\n",
2303 | "[25, 14, 52, 44, 53, 17, 12, 9, 61, 11]\n",
2304 | "ZaculllVoh\n",
2305 | "[20, 59, 11, 39, 35, 35, 53, 6, 59, 33]\n",
2306 | "trumyerlip\n",
2307 | "[56, 14, 39, 15, 17, 50, 43, 53, 61, 3]\n",
2308 | "ruitampolr\n",
2309 | "[13, 36, 19, 56, 29, 15, 3, 59, 35, 53]\n"
2310 | ],
2311 | "name": "stdout"
2312 | },
2313 | {
2314 | "output_type": "stream",
2315 | "text": [
2316 | "100%|██████████| 208/208 [00:14<00:00, 14.83it/s]\n"
2317 | ],
2318 | "name": "stderr"
2319 | },
2320 | {
2321 | "output_type": "stream",
2322 | "text": [
2323 | "loss: 23.1785945892334\n",
2324 | "ovinarmege\n",
2325 | "[54, 40, 19, 48, 29, 43, 37, 29, 22, 52]\n"
2326 | ],
2327 | "name": "stdout"
2328 | },
2329 | {
2330 | "output_type": "stream",
2331 | "text": [
2332 | "\r 0%| | 0/208 [00:00, ?it/s]"
2333 | ],
2334 | "name": "stderr"
2335 | },
2336 | {
2337 | "output_type": "stream",
2338 | "text": [
2339 | "========= Results: epoch 7 of 10 =========\n",
2340 | "train loss: 23.35| valid loss: 23.35\n",
2341 | "\n",
2342 | "========= Epoch 8 of 10 =========\n"
2343 | ],
2344 | "name": "stdout"
2345 | },
2346 | {
2347 | "output_type": "stream",
2348 | "text": [
2349 | " 1%|▏ | 3/208 [00:00<00:45, 4.53it/s]"
2350 | ],
2351 | "name": "stderr"
2352 | },
2353 | {
2354 | "output_type": "stream",
2355 | "text": [
2356 | "loss: 23.04974365234375\n",
2357 | "daSytatana\n",
2358 | "[20, 59, 53, 52, 56, 29, 48, 29, 21, 29]\n",
2359 | "indosetckg\n",
2360 | "[42, 21, 44, 59, 31, 52, 60, 11, 57, 1]\n",
2361 | "knitervers\n",
2362 | "[42, 21, 19, 48, 50, 43, 40, 50, 43, 32]\n",
2363 | "sulHberian\n",
2364 | "[31, 39, 35, 19, 47, 50, 43, 19, 29, 21]\n",
2365 | "meaphiUant\n",
2366 | "[20, 52, 54, 3, 9, 61, 37, 59, 21, 23]\n"
2367 | ],
2368 | "name": "stdout"
2369 | },
2370 | {
2371 | "output_type": "stream",
2372 | "text": [
2373 | " 25%|██▌ | 53/208 [00:03<00:10, 14.32it/s]"
2374 | ],
2375 | "name": "stderr"
2376 | },
2377 | {
2378 | "output_type": "stream",
2379 | "text": [
2380 | "loss: 23.460845947265625\n",
2381 | "bratsandew\n",
2382 | "[55, 49, 29, 23, 32, 29, 21, 22, 52, 56]\n",
2383 | "jonOthosse\n",
2384 | "[20, 59, 37, 29, 23, 9, 52, 60, 32, 52]\n",
2385 | "Tewaelvere\n",
2386 | "[20, 52, 0, 29, 50, 35, 40, 50, 43, 50]\n",
2387 | "panventebo\n",
2388 | "[56, 29, 21, 40, 50, 21, 23, 50, 38, 59]\n",
2389 | "calllccink\n",
2390 | "[20, 29, 35, 35, 35, 11, 11, 19, 21, 57]\n"
2391 | ],
2392 | "name": "stdout"
2393 | },
2394 | {
2395 | "output_type": "stream",
2396 | "text": [
2397 | " 50%|████▉ | 103/208 [00:07<00:07, 14.11it/s]"
2398 | ],
2399 | "name": "stderr"
2400 | },
2401 | {
2402 | "output_type": "stream",
2403 | "text": [
2404 | "loss: 23.10556411743164\n",
2405 | "Sinecogles\n",
2406 | "[20, 61, 37, 19, 48, 52, 22, 53, 52, 60]\n",
2407 | "wakundenth\n",
2408 | "[34, 29, 28, 42, 21, 48, 52, 21, 23, 33]\n",
2409 | "sproctinse\n",
2410 | "[31, 56, 49, 54, 11, 23, 61, 21, 32, 50]\n",
2411 | "spereniogr\n",
2412 | "[31, 56, 50, 14, 52, 37, 19, 29, 1, 43]\n",
2413 | "semalalatr\n",
2414 | "[31, 54, 37, 29, 35, 29, 35, 29, 23, 49]\n"
2415 | ],
2416 | "name": "stdout"
2417 | },
2418 | {
2419 | "output_type": "stream",
2420 | "text": [
2421 | " 74%|███████▎ | 153/208 [00:10<00:03, 13.99it/s]"
2422 | ],
2423 | "name": "stderr"
2424 | },
2425 | {
2426 | "output_type": "stream",
2427 | "text": [
2428 | "loss: 22.967063903808594\n",
2429 | "epoulodyat\n",
2430 | "[54, 3, 45, 39, 35, 45, 48, 17, 29, 23]\n",
2431 | "ebssernaer\n",
2432 | "[54, 16, 60, 23, 50, 43, 37, 29, 52, 14]\n",
2433 | "Meascomuch\n",
2434 | "[20, 52, 54, 60, 23, 45, 18, 27, 11, 9]\n",
2435 | "cromicenon\n",
2436 | "[11, 49, 59, 37, 19, 48, 52, 37, 59, 37]\n",
2437 | "dialddfula\n",
2438 | "[20, 19, 29, 35, 44, 44, 62, 39, 35, 29]\n"
2439 | ],
2440 | "name": "stdout"
2441 | },
2442 | {
2443 | "output_type": "stream",
2444 | "text": [
2445 | " 98%|█████████▊| 203/208 [00:13<00:00, 14.81it/s]"
2446 | ],
2447 | "name": "stderr"
2448 | },
2449 | {
2450 | "output_type": "stream",
2451 | "text": [
2452 | "loss: 23.592716217041016\n",
2453 | "cipulperdc\n",
2454 | "[20, 61, 41, 42, 21, 56, 59, 43, 44, 11]\n",
2455 | "suloiansfr\n",
2456 | "[31, 39, 35, 45, 19, 29, 21, 32, 25, 14]\n",
2457 | "pwivuryssi\n",
2458 | "[56, 0, 61, 40, 7, 14, 52, 60, 32, 61]\n",
2459 | "damemoitab\n",
2460 | "[20, 29, 37, 52, 15, 45, 19, 48, 29, 38]\n",
2461 | "porerthomn\n",
2462 | "[3, 59, 43, 50, 43, 12, 9, 59, 37, 53]\n"
2463 | ],
2464 | "name": "stdout"
2465 | },
2466 | {
2467 | "output_type": "stream",
2468 | "text": [
2469 | "100%|██████████| 208/208 [00:14<00:00, 14.75it/s]\n"
2470 | ],
2471 | "name": "stderr"
2472 | },
2473 | {
2474 | "output_type": "stream",
2475 | "text": [
2476 | "loss: 23.200260162353516\n",
2477 | "sulinosser\n",
2478 | "[31, 39, 35, 19, 21, 52, 60, 32, 50, 43]\n"
2479 | ],
2480 | "name": "stdout"
2481 | },
2482 | {
2483 | "output_type": "stream",
2484 | "text": [
2485 | "\r 0%| | 0/208 [00:00, ?it/s]"
2486 | ],
2487 | "name": "stderr"
2488 | },
2489 | {
2490 | "output_type": "stream",
2491 | "text": [
2492 | "========= Results: epoch 8 of 10 =========\n",
2493 | "train loss: 23.29| valid loss: 23.29\n",
2494 | "\n",
2495 | "========= Epoch 9 of 10 =========\n"
2496 | ],
2497 | "name": "stdout"
2498 | },
2499 | {
2500 | "output_type": "stream",
2501 | "text": [
2502 | " 1%|▏ | 3/208 [00:00<00:44, 4.64it/s]"
2503 | ],
2504 | "name": "stderr"
2505 | },
2506 | {
2507 | "output_type": "stream",
2508 | "text": [
2509 | "loss: 23.086050033569336\n",
2510 | "seatuedasi\n",
2511 | "[31, 52, 29, 23, 36, 52, 44, 59, 37, 19]\n",
2512 | "lalocolice\n",
2513 | "[20, 54, 35, 59, 11, 59, 35, 19, 48, 52]\n",
2514 | "inverlesca\n",
2515 | "[42, 21, 40, 50, 43, 53, 52, 60, 11, 29]\n",
2516 | "donctabyli\n",
2517 | "[20, 59, 21, 11, 23, 29, 38, 7, 35, 19]\n",
2518 | "tonneoomme\n",
2519 | "[56, 59, 21, 53, 52, 54, 7, 15, 18, 50]\n"
2520 | ],
2521 | "name": "stdout"
2522 | },
2523 | {
2524 | "output_type": "stream",
2525 | "text": [
2526 | " 25%|██▌ | 53/208 [00:03<00:10, 14.31it/s]"
2527 | ],
2528 | "name": "stderr"
2529 | },
2530 | {
2531 | "output_type": "stream",
2532 | "text": [
2533 | "loss: 23.360929489135742\n",
2534 | "serptoucka\n",
2535 | "[31, 29, 43, 3, 23, 45, 39, 11, 57, 29]\n",
2536 | "dmediPineb\n",
2537 | "[22, 18, 50, 44, 61, 37, 61, 37, 29, 38]\n",
2538 | "tensushest\n",
2539 | "[56, 50, 21, 31, 39, 32, 9, 52, 60, 56]\n",
2540 | "coreatimor\n",
2541 | "[20, 59, 37, 52, 29, 23, 61, 37, 59, 43]\n",
2542 | "gAplomalin\n",
2543 | "[20, 54, 3, 53, 52, 18, 29, 35, 19, 21]\n"
2544 | ],
2545 | "name": "stdout"
2546 | },
2547 | {
2548 | "output_type": "stream",
2549 | "text": [
2550 | " 50%|████▉ | 103/208 [00:07<00:07, 14.35it/s]"
2551 | ],
2552 | "name": "stderr"
2553 | },
2554 | {
2555 | "output_type": "stream",
2556 | "text": [
2557 | "loss: 23.229515075683594\n",
2558 | "dommizerox\n",
2559 | "[20, 7, 15, 18, 19, 48, 50, 43, 45, 22]\n",
2560 | "chinckirio\n",
2561 | "[12, 9, 19, 21, 11, 57, 7, 43, 19, 45]\n",
2562 | "ingidobign\n",
2563 | "[42, 21, 22, 19, 48, 52, 8, 61, 26, 37]\n",
2564 | "Inchapentr\n",
2565 | "[42, 21, 11, 9, 29, 3, 52, 21, 23, 14]\n",
2566 | "corvoxtita\n",
2567 | "[20, 59, 43, 40, 59, 21, 23, 61, 48, 29]\n"
2568 | ],
2569 | "name": "stdout"
2570 | },
2571 | {
2572 | "output_type": "stream",
2573 | "text": [
2574 | " 74%|███████▎ | 153/208 [00:10<00:03, 14.94it/s]"
2575 | ],
2576 | "name": "stderr"
2577 | },
2578 | {
2579 | "output_type": "stream",
2580 | "text": [
2581 | "loss: 23.115970611572266\n",
2582 | "shatengmal\n",
2583 | "[12, 9, 29, 23, 50, 21, 22, 18, 59, 53]\n",
2584 | "agerablecs\n",
2585 | "[54, 26, 50, 43, 29, 38, 53, 52, 60, 32]\n",
2586 | "bettinnalp\n",
2587 | "[8, 52, 23, 23, 61, 48, 37, 29, 35, 3]\n",
2588 | "arvervedri\n",
2589 | "[54, 43, 40, 50, 43, 40, 50, 44, 14, 61]\n",
2590 | "satiltiont\n",
2591 | "[31, 29, 23, 7, 35, 23, 61, 59, 21, 23]\n"
2592 | ],
2593 | "name": "stdout"
2594 | },
2595 | {
2596 | "output_type": "stream",
2597 | "text": [
2598 | " 98%|█████████▊| 203/208 [00:13<00:00, 14.14it/s]"
2599 | ],
2600 | "name": "stderr"
2601 | },
2602 | {
2603 | "output_type": "stream",
2604 | "text": [
2605 | "loss: 23.269947052001953\n",
2606 | "Mutrinesti\n",
2607 | "[20, 27, 23, 49, 61, 37, 52, 60, 23, 61]\n",
2608 | "Miatoguian\n",
2609 | "[20, 19, 29, 11, 45, 13, 36, 19, 29, 21]\n",
2610 | "nisherpher\n",
2611 | "[20, 19, 60, 9, 29, 43, 12, 9, 7, 14]\n",
2612 | "sUquuspedu\n",
2613 | "[31, 54, 13, 36, 52, 60, 32, 50, 44, 27]\n",
2614 | "peneclerbo\n",
2615 | "[56, 52, 37, 52, 11, 53, 50, 43, 24, 59]\n"
2616 | ],
2617 | "name": "stdout"
2618 | },
2619 | {
2620 | "output_type": "stream",
2621 | "text": [
2622 | "100%|██████████| 208/208 [00:14<00:00, 14.83it/s]\n"
2623 | ],
2624 | "name": "stderr"
2625 | },
2626 | {
2627 | "output_type": "stream",
2628 | "text": [
2629 | "loss: 23.198766708374023\n",
2630 | "unvealiayt\n",
2631 | "[42, 21, 40, 50, 29, 35, 19, 29, 52, 23]\n"
2632 | ],
2633 | "name": "stdout"
2634 | },
2635 | {
2636 | "output_type": "stream",
2637 | "text": [
2638 | "\r 0%| | 0/208 [00:00, ?it/s]"
2639 | ],
2640 | "name": "stderr"
2641 | },
2642 | {
2643 | "output_type": "stream",
2644 | "text": [
2645 | "========= Results: epoch 9 of 10 =========\n",
2646 | "train loss: 23.22| valid loss: 23.23\n",
2647 | "\n",
2648 | "========= Epoch 10 of 10 =========\n"
2649 | ],
2650 | "name": "stdout"
2651 | },
2652 | {
2653 | "output_type": "stream",
2654 | "text": [
2655 | " 1%|▏ | 3/208 [00:00<00:43, 4.69it/s]"
2656 | ],
2657 | "name": "stderr"
2658 | },
2659 | {
2660 | "output_type": "stream",
2661 | "text": [
2662 | "loss: 23.117088317871094\n",
2663 | "dorinestou\n",
2664 | "[20, 59, 43, 19, 21, 52, 60, 23, 45, 39]\n",
2665 | "bravicahle\n",
2666 | "[55, 49, 54, 40, 61, 11, 29, 9, 53, 52]\n",
2667 | "purymymier\n",
2668 | "[56, 39, 43, 17, 15, 17, 18, 19, 50, 43]\n",
2669 | "policanint\n",
2670 | "[56, 7, 35, 19, 48, 29, 37, 19, 21, 23]\n",
2671 | "amumommvyo\n",
2672 | "[54, 15, 39, 37, 59, 15, 18, 40, 50, 45]\n"
2673 | ],
2674 | "name": "stdout"
2675 | },
2676 | {
2677 | "output_type": "stream",
2678 | "text": [
2679 | " 25%|██▌ | 53/208 [00:03<00:11, 13.94it/s]"
2680 | ],
2681 | "name": "stderr"
2682 | },
2683 | {
2684 | "output_type": "stream",
2685 | "text": [
2686 | "loss: 23.243858337402344\n",
2687 | "emephonema\n",
2688 | "[54, 37, 52, 3, 9, 54, 37, 52, 18, 29]\n",
2689 | "chesmalcil\n",
2690 | "[12, 9, 52, 60, 18, 29, 35, 11, 7, 35]\n",
2691 | "dessatatry\n",
2692 | "[20, 52, 60, 32, 29, 23, 29, 23, 14, 52]\n",
2693 | "entionimir\n",
2694 | "[42, 21, 23, 61, 59, 37, 19, 37, 50, 43]\n",
2695 | "Mutistilet\n",
2696 | "[20, 27, 23, 61, 60, 23, 61, 53, 52, 23]\n"
2697 | ],
2698 | "name": "stdout"
2699 | },
2700 | {
2701 | "output_type": "stream",
2702 | "text": [
2703 | " 50%|████▉ | 103/208 [00:07<00:07, 14.42it/s]"
2704 | ],
2705 | "name": "stderr"
2706 | },
2707 | {
2708 | "output_type": "stream",
2709 | "text": [
2710 | "loss: 22.98015022277832\n",
2711 | "cessiconri\n",
2712 | "[20, 52, 60, 32, 61, 11, 59, 21, 14, 19]\n",
2713 | "suslollmat\n",
2714 | "[31, 39, 32, 53, 52, 35, 35, 18, 29, 23]\n",
2715 | "ouretiomed\n",
2716 | "[54, 27, 14, 52, 23, 61, 59, 37, 50, 44]\n",
2717 | "aptsechere\n",
2718 | "[54, 3, 23, 31, 52, 11, 9, 50, 14, 52]\n",
2719 | "averebopar\n",
2720 | "[54, 40, 50, 14, 52, 24, 59, 3, 29, 43]\n"
2721 | ],
2722 | "name": "stdout"
2723 | },
2724 | {
2725 | "output_type": "stream",
2726 | "text": [
2727 | " 74%|███████▎ | 153/208 [00:10<00:03, 14.57it/s]"
2728 | ],
2729 | "name": "stderr"
2730 | },
2731 | {
2732 | "output_type": "stream",
2733 | "text": [
2734 | "loss: 23.266876220703125\n",
2735 | "unzesticed\n",
2736 | "[42, 21, 48, 52, 60, 23, 61, 48, 52, 37]\n",
2737 | "Ninglulemi\n",
2738 | "[20, 19, 21, 22, 49, 27, 14, 52, 18, 19]\n",
2739 | "hipanveseg\n",
2740 | "[20, 19, 48, 29, 21, 40, 50, 14, 52, 34]\n",
2741 | "inpertheco\n",
2742 | "[42, 21, 32, 50, 43, 23, 33, 52, 11, 49]\n",
2743 | "hequalicec\n",
2744 | "[33, 52, 13, 36, 29, 35, 19, 11, 52, 11]\n"
2745 | ],
2746 | "name": "stdout"
2747 | },
2748 | {
2749 | "output_type": "stream",
2750 | "text": [
2751 | " 98%|█████████▊| 203/208 [00:13<00:00, 14.69it/s]"
2752 | ],
2753 | "name": "stderr"
2754 | },
2755 | {
2756 | "output_type": "stream",
2757 | "text": [
2758 | "loss: 23.194381713867188\n",
2759 | "jeassisico\n",
2760 | "[20, 52, 54, 60, 32, 61, 37, 19, 11, 59]\n",
2761 | "brouroster\n",
2762 | "[55, 49, 54, 27, 14, 45, 31, 56, 50, 43]\n",
2763 | "guaBerinal\n",
2764 | "[13, 36, 29, 23, 50, 43, 19, 48, 29, 35]\n",
2765 | "nerigesoch\n",
2766 | "[20, 50, 43, 19, 1, 52, 60, 59, 11, 9]\n",
2767 | "bricoyatre\n",
2768 | "[55, 49, 61, 11, 59, 37, 29, 23, 14, 52]\n"
2769 | ],
2770 | "name": "stdout"
2771 | },
2772 | {
2773 | "output_type": "stream",
2774 | "text": [
2775 | "100%|██████████| 208/208 [00:13<00:00, 14.90it/s]\n"
2776 | ],
2777 | "name": "stderr"
2778 | },
2779 | {
2780 | "output_type": "stream",
2781 | "text": [
2782 | "loss: 23.0813045501709\n",
2783 | "dafletinte\n",
2784 | "[20, 54, 58, 53, 52, 23, 61, 21, 23, 50]\n",
2785 | "========= Results: epoch 10 of 10 =========\n",
2786 | "train loss: 23.18| valid loss: 23.19\n",
2787 | "\n"
2788 | ],
2789 | "name": "stdout"
2790 | }
2791 | ]
2792 | },
2793 | {
2794 | "cell_type": "markdown",
2795 | "metadata": {
2796 | "id": "zymBj9QrDHRM"
2797 | },
2798 | "source": [
2799 | "You may wish to try different values of $N$ and see what the impact on sample quality is."
2800 | ]
2801 | },
2802 | {
2803 | "cell_type": "code",
2804 | "metadata": {
2805 | "id": "auBibYUTtIom",
2806 | "colab": {
2807 | "base_uri": "https://localhost:8080/"
2808 | },
2809 | "outputId": "ad9f161c-21dc-40a6-ce30-759d9c40c606"
2810 | },
2811 | "source": [
2812 | "x = torch.tensor(encode(\"quack\")).unsqueeze(0)\n",
2813 | "T = torch.tensor([5])\n",
2814 | "print(model.viterbi(x,T))\n",
2815 | "\n",
2816 | "x = torch.tensor(encode(\"quick\")).unsqueeze(0)\n",
2817 | "T = torch.tensor([5])\n",
2818 | "print(model.viterbi(x,T))\n",
2819 | "\n",
2820 | "x = torch.tensor(encode(\"qurck\")).unsqueeze(0)\n",
2821 | "T = torch.tensor([5])\n",
2822 | "print(model.viterbi(x,T)) # should have lower probability---in English only vowels follow \"qu\"\n",
2823 | "\n",
2824 | "x = torch.tensor(encode(\"qiick\")).unsqueeze(0)\n",
2825 | "T = torch.tensor([5])\n",
2826 | "print(model.viterbi(x,T)) # should have lower probability---in English only \"u\" follows \"q\"\n"
2827 | ],
2828 | "execution_count": 29,
2829 | "outputs": [
2830 | {
2831 | "output_type": "stream",
2832 | "text": [
2833 | "([[13, 36, 29, 11, 57]], tensor([[-12.3761]], device='cuda:0', grad_fn=))\n",
2834 | "([[13, 36, 19, 11, 57]], tensor([[-12.9984]], device='cuda:0', grad_fn=))\n",
2835 | "([[13, 36, 43, 11, 57]], tensor([[-18.9938]], device='cuda:0', grad_fn=))\n",
2836 | "([[13, 36, 19, 11, 57]], tensor([[-21.7014]], device='cuda:0', grad_fn=))\n"
2837 | ],
2838 | "name": "stdout"
2839 | }
2840 | ]
2841 | },
2842 | {
2843 | "cell_type": "markdown",
2844 | "metadata": {
2845 | "id": "7eZeQXWjhDev"
2846 | },
2847 | "source": [
2848 | "## Conclusion\n",
2849 | "\n",
2850 | "HMMs used to be very popular in natural language processing, but they have largely been overshadowed by neural network models like RNNs and Transformers. Still, it is fun and instructive to study the HMM; some commonly used machine learning techniques like [Connectionist Temporal Classification](https://www.cs.toronto.edu/~graves/icml_2006.pdf) are inspired by HMM methods. HMMs are [still used in conjunction with neural networks in speech recognition](https://arxiv.org/abs/1811.07453), where the assumption of a one-hot state makes sense for modelling phonemes, which are spoken one at a time."
2851 | ]
2852 | },
2853 | {
2854 | "cell_type": "markdown",
2855 | "metadata": {
2856 | "id": "gXQOBz5zqe10"
2857 | },
2858 | "source": [
2859 | "## Acknowledgments\n",
2860 | "\n",
2861 | "This notebook is based partly on Lawrence Rabiner's excellent article \"[A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition](https://www.cs.cmu.edu/~cga/behavior/rabiner1.pdf)\", which you may also like to check out. Thanks also to Dima Serdyuk and Kyle Gorman for their feedback on the draft."
2862 | ]
2863 | }
2864 | ]
2865 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # HMMs in PyTorch
2 |
3 | This repo contains code for Hidden Markov Models (HMMs) in PyTorch, including the forward algorithm, the Viterbi algorithm, and sampling. Training is implemented by backpropagating the negative log-likelihood from the forward algorithm, instead of using the EM algorithm.
4 |
5 | You can read a notebook which covers the theory of HMMs and implements the model in PyTorch piece-by-piece [here](https://colab.research.google.com/drive/1IUe9lfoIiQsL49atSOgxnCmMR_zJazKI).
6 |
--------------------------------------------------------------------------------
/data.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.utils.data
3 | from collections import Counter
4 | import os
5 | from sklearn.model_selection import train_test_split
6 |
7 | class Config:
8 | def __init__(self,N,path):
9 | self.N = N
10 | self.path = path
11 |
12 | def read_config(N, path):
13 | config = Config(N=N,path=path)
14 | return config
15 |
16 | def get_datasets(config):
17 | path = config.path
18 |
19 | lines = []
20 | for filename in os.listdir(os.path.join(path, "train")):
21 | with open(os.path.join(path, "train", filename), "r") as f:
22 | lines_ = f.readlines()
23 | #lines_[-1] += '\n'
24 | lines += lines_
25 |
26 | # get input and output alphabets
27 | Sx = list(Counter(("".join(lines))).keys()) # set of possible output letters
28 | train_lines, valid_lines = train_test_split(lines, test_size=0.1, random_state=42)
29 | train_dataset = TextDataset(train_lines, Sx)
30 | valid_dataset = TextDataset(valid_lines, Sx)
31 |
32 | config.M = len(Sx)
33 | config.Sx = Sx
34 |
35 | return train_dataset, valid_dataset
36 |
37 | class TextDataset(torch.utils.data.Dataset):
38 | def __init__(self, lines, Sx):
39 | self.lines = lines # list of strings
40 | self.Sx = Sx
41 | pad_and_one_hot = PadAndOneHot(self.Sx) # function for generating a minibatch from strings
42 | self.loader = torch.utils.data.DataLoader(self, batch_size=32, num_workers=1, shuffle=True, collate_fn=pad_and_one_hot)
43 |
44 | def __len__(self):
45 | return len(self.lines)
46 |
47 | def __getitem__(self, idx):
48 | line = self.lines[idx].lstrip(" ").rstrip("\n").rstrip(" ").rstrip("\n")
49 | return line
50 |
51 | #def one_hot(letters, M):
52 | # """
53 | # letters : LongTensor of shape (batch size, sequence length)
54 | # M : integer
55 | # Convert batch of integer letter indices to one-hot vectors of dimension M (# of possible letters).
56 | # """
57 |
58 | # out = torch.zeros(letters.shape[0], letters.shape[1], M)
59 | # for i in range(0, letters.shape[0]):
60 | # for t in range(0, letters.shape[1]):
61 | # out[i, t, letters[i,t]] = 1
62 | # return out
63 |
64 | class PadAndOneHot:
65 | def __init__(self, Sx):
66 | self.Sx = Sx
67 |
68 | def __call__(self, batch):
69 | """
70 | Returns a minibatch of strings, one-hot encoded and padded to have the same length.
71 | """
72 | x = []
73 | batch_size = len(batch)
74 | for index in range(batch_size):
75 | x_ = batch[index]
76 | if "\n" in x_:
77 | print(x_)
78 | sys.exit()
79 |
80 | # convert letters to integers
81 | x.append([self.Sx.index(c) for c in x_])
82 |
83 | # pad all sequences with 0 to have same length
84 | x_lengths = [len(x_) for x_ in x]
85 | T = max(x_lengths)
86 | for index in range(batch_size):
87 | x[index] += [0] * (T - len(x[index]))
88 | x[index] = torch.tensor(x[index])
89 |
90 | # stack into single tensor and one-hot encode integer labels
91 | x = torch.stack(x) #one_hot(torch.stack(x), len(self.Sx))
92 | x_lengths = torch.tensor(x_lengths)
93 |
94 | return (x,x_lengths)
95 |
--------------------------------------------------------------------------------
/helper_functions.py:
--------------------------------------------------------------------------------
1 | import torch
2 |
3 | def one_hot(letters, S):
4 | """
5 | letters : LongTensor of shape (batch size, sequence length)
6 | S : integer
7 |
8 | Convert batch of integer letter indices to one-hot vectors of dimension S (# of possible letters).
9 | """
10 |
11 | out = torch.zeros(letters.shape[0], letters.shape[1], S)
12 | for i in range(0, letters.shape[0]):
13 | for t in range(0, letters.shape[1]):
14 | out[i, t, letters[i,t]] = 1
15 | return out
16 |
17 | def one_hot_to_string(input, S):
18 | """
19 | input : Tensor of shape (T, |Sx|)
20 | S : list of characters (alphabet, Sx or Sy)
21 | """
22 |
23 | return "".join([S[c] for c in input.max(dim=1)[1]]).rstrip()
24 |
--------------------------------------------------------------------------------
/img/hmm.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lorenlugosch/pytorch_HMM/40859fdf356ed7fd63913af704f351d81201a099/img/hmm.png
--------------------------------------------------------------------------------
/img/selfies.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lorenlugosch/pytorch_HMM/40859fdf356ed7fd63913af704f351d81201a099/img/selfies.png
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | import torch
2 | from models import HMM
3 | from data import get_datasets, read_config
4 | from training import Trainer
5 |
6 | # Generate datasets from text file
7 | path = "data"
8 | N = 128
9 | config = read_config(N,path)
10 | train_dataset, valid_dataset = get_datasets(config)
11 | checkpoint_path = "."
12 |
13 | # Initialize model
14 | model = HMM(config=config)
15 |
16 | # Train the model
17 | num_epochs = 10
18 | trainer = Trainer(model, config, lr=0.003)
19 | trainer.load_checkpoint(checkpoint_path)
20 |
21 | for epoch in range(num_epochs):
22 | print("========= Epoch %d of %d =========" % (epoch+1, num_epochs))
23 | train_loss = trainer.train(train_dataset)
24 | valid_loss = trainer.test(valid_dataset)
25 | trainer.save_checkpoint(epoch, checkpoint_path)
26 |
27 | print("========= Results: epoch %d of %d =========" % (epoch+1, num_epochs))
28 | print("train loss: %.2f| valid loss: %.2f\n" % (train_loss, valid_loss) )
29 |
30 |
31 |
--------------------------------------------------------------------------------
/models.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import genbmm
3 |
4 | class HMM(torch.nn.Module):
5 | """
6 | Hidden Markov Model.
7 | (For now, discrete observations only.)
8 | - forward(): computes the log probability of an observation sequence.
9 | - viterbi(): computes the most likely state sequence.
10 | - sample(): draws a sample from p(x).
11 | """
12 | def __init__(self, config):
13 | super(HMM, self).__init__()
14 | self.M = config.M # number of possible observations
15 | self.N = config.N # number of states
16 | self.unnormalized_state_priors = torch.nn.Parameter(torch.randn(self.N))
17 | self.transition_model = TransitionModel(self.N)
18 | self.emission_model = EmissionModel(self.N,self.M)
19 | self.is_cuda = torch.cuda.is_available()
20 | if self.is_cuda: self.cuda()
21 |
22 | def forward(self, x, T):
23 | """
24 | x : IntTensor of shape (batch size, T_max)
25 | T : IntTensor of shape (batch size)
26 |
27 | Compute log p(x) for each example in the batch.
28 | T = length of each example
29 | """
30 | if self.is_cuda:
31 | x = x.cuda()
32 | T = T.cuda()
33 |
34 | batch_size = x.shape[0]; T_max = x.shape[1]
35 | log_state_priors = torch.nn.functional.log_softmax(self.unnormalized_state_priors, dim=0)
36 | log_alpha = torch.zeros(batch_size, T_max, self.N)
37 | if self.is_cuda: log_alpha = log_alpha.cuda()
38 |
39 | log_alpha[:, 0, :] = self.emission_model(x[:,0]) + log_state_priors
40 | print(log_alpha[:, 0, :])
41 | for t in range(1, T_max):
42 | log_alpha[:, t, :] = self.emission_model(x[:,t]) + self.transition_model(log_alpha[:, t-1, :], use_max=False)
43 | print(log_alpha[:, t, :])
44 |
45 | log_sums = log_alpha.logsumexp(dim=2)
46 |
47 | # Select the sum for the final timestep (each x has different length).
48 | log_probs = torch.gather(log_sums, 1, T.view(-1,1) - 1)
49 | return log_probs
50 |
51 | def sample(self, T=10):
52 | state_priors = torch.nn.functional.softmax(self.unnormalized_state_priors, dim=0)
53 | transition_matrix = torch.nn.functional.softmax(self.transition_model.unnormalized_transition_matrix, dim=0)
54 | emission_matrix = torch.nn.functional.softmax(self.emission_model.unnormalized_emission_matrix, dim=1)
55 |
56 | # sample initial state
57 | z_t = torch.distributions.categorical.Categorical(state_priors).sample().item()
58 | z = []
59 | x = []
60 | z.append(z_t)
61 | for t in range(0,T):
62 | # sample emission
63 | x_t = torch.distributions.categorical.Categorical(emission_matrix[z_t]).sample().item()
64 | x.append(x_t)
65 |
66 | # sample transition
67 | z_t = torch.distributions.categorical.Categorical(transition_matrix[:,z_t]).sample().item()
68 | if t < T-1: z.append(z_t)
69 |
70 | return x, z
71 |
72 | def viterbi(self, x, T):
73 | """
74 | x : IntTensor of shape (batch size, T_max)
75 | T : IntTensor of shape (batch size)
76 |
77 | Find argmax_z log p(z|x) for each (x) in the batch.
78 | """
79 | if self.is_cuda:
80 | x = x.cuda()
81 | T = T.cuda()
82 |
83 | batch_size = x.shape[0]; T_max = x.shape[1]
84 | log_state_priors = torch.nn.functional.log_softmax(self.unnormalized_state_priors, dim=0)
85 | log_delta = torch.zeros(batch_size, T_max, self.N).float()
86 | psi = torch.zeros(batch_size, T_max, self.N).long()
87 | if self.is_cuda:
88 | log_delta = log_delta.cuda()
89 | psi = psi.cuda()
90 |
91 | log_delta[:, 0, :] = self.emission_model(x[:,0]) + log_state_priors
92 | for t in range(1, T_max):
93 | max_val, argmax_val = self.transition_model(log_delta[:, t-1, :], use_max=True)
94 | log_delta[:, t, :] = self.emission_model(x[:,t]) + max_val
95 | psi[:, t, :] = argmax_val
96 |
97 | # Get the probability of the best path
98 | log_max = log_delta.max(dim=2)[0]
99 | best_path_scores = torch.gather(log_max, 1, T.view(-1,1) - 1)
100 |
101 | # This next part is a bit tricky to parallelize across the batch,
102 | # so we will do it separately for each example.
103 | z_star = []
104 | for i in range(0, batch_size):
105 | z_star_i = [ log_delta[i, T[i] - 1, :].max(dim=0)[1].item() ]
106 | for t in range(T[i] - 1, 0, -1):
107 | z_t = psi[i, t, z_star_i[0]].item()
108 | z_star_i.insert(0, z_t)
109 |
110 | z_star.append(z_star_i)
111 |
112 | return z_star, best_path_scores
113 |
114 | def log_domain_matmul(log_A, log_B, use_max=False):
115 | """
116 | log_A : m x n
117 | log_B : n x p
118 |
119 | output : m x p matrix
120 |
121 | Normally, a matrix multiplication
122 | computes out_{i,j} = sum_k A_{i,k} x B_{k,j}
123 |
124 | A log domain matrix multiplication
125 | computes out_{i,j} = logsumexp_k log_A_{i,k} + log_B_{k,j}
126 |
127 | This is needed for numerical stability
128 | when A and B are probability matrices.
129 | """
130 | #m = log_A.shape[0]
131 | #n = log_A.shape[1]
132 | #p = log_B.shape[1]
133 |
134 | #log_A_expanded = torch.stack([log_A] * p, dim=2)
135 | #log_B_expanded = torch.stack([log_B] * m, dim=0)
136 |
137 | #elementwise_sum = log_A_expanded + log_B_expanded
138 | #out = torch.logsumexp(elementwise_sum, dim=1)
139 |
140 | out = genbmm.logbmm(log_A.unsqueeze(0).contiguous(), log_B.unsqueeze(1).contiguous())[0]
141 |
142 | return out
143 |
144 | def maxmul(log_A, log_B):
145 | m = log_A.shape[0]
146 | n = log_A.shape[1]
147 | p = log_B.shape[1]
148 |
149 | log_A_expanded = torch.stack([log_A] * p, dim=2)
150 | log_B_expanded = torch.stack([log_B] * m, dim=0)
151 |
152 | elementwise_sum = log_A_expanded + log_B_expanded
153 | out1, out2 = torch.max(elementwise_sum, dim=1)
154 |
155 | return out1, out2
156 |
157 | class TransitionModel(torch.nn.Module):
158 | """
159 | - forward(): computes the log probability of a transition.
160 | - sample(): given a previous state, sample a new state.
161 | """
162 | def __init__(self, N):
163 | super(TransitionModel, self).__init__()
164 | self.N = N # number of states
165 | self.unnormalized_transition_matrix = torch.nn.Parameter(torch.randn(N,N))
166 |
167 | def forward(self, log_alpha, use_max):
168 | """
169 | log_alpha : Tensor of shape (batch size, N)
170 |
171 | Multiply previous timestep's alphas by transition matrix (in log domain)
172 | """
173 | # Each col needs to add up to 1 (in probability domain)
174 | log_transition_matrix = torch.nn.functional.log_softmax(self.unnormalized_transition_matrix, dim=0)
175 |
176 | # Matrix multiplication in the log domain
177 | #out = genbmm.logbmm(log_alpha.unsqueeze(0).contiguous(), transition_matrix.unsqueeze(0).contiguous())[0]
178 | if use_max:
179 | out1, out2 = maxmul(log_transition_matrix, log_alpha.transpose(0,1))
180 | return out1.transpose(0,1), out2.transpose(0,1)
181 | else:
182 | out = log_domain_matmul(log_transition_matrix, log_alpha.transpose(0,1))
183 | out = out.transpose(0,1)
184 | return out
185 |
186 | class EmissionModel(torch.nn.Module):
187 | """
188 | - forward(): computes the log probability of an observation.
189 | - sample(): given a state, sample an observation for that state.
190 | """
191 | def __init__(self, N, M):
192 | super(EmissionModel, self).__init__()
193 | self.N = N # number of states
194 | self.M = M # number of possible observations
195 | self.unnormalized_emission_matrix = torch.nn.Parameter(torch.randn(N,M))
196 |
197 | def forward(self, x_t):
198 | """
199 | x_t : LongTensor of shape (batch size)
200 |
201 | Get observation probabilities
202 | """
203 | # Each col needs to add up to 1 (in probability domain)
204 | emission_matrix = torch.nn.functional.log_softmax(self.unnormalized_emission_matrix, dim=1)
205 | out = emission_matrix[:, x_t].transpose(0,1)
206 |
207 | return out
208 |
--------------------------------------------------------------------------------
/training.py:
--------------------------------------------------------------------------------
1 | import torch
2 | from tqdm import tqdm # for displaying progress bar
3 | import os
4 | import pandas as pd
5 |
6 | class Trainer:
7 | def __init__(self, model, config, lr):
8 | self.model = model
9 | self.config = config
10 | self.lr = lr
11 | self.optimizer = torch.optim.Adam(model.parameters(), lr=self.lr, weight_decay=0.00001)
12 | self.scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(self.optimizer, 'min')
13 | self.train_df = pd.DataFrame(columns=["loss","lr"])
14 | self.valid_df = pd.DataFrame(columns=["loss","lr"])
15 |
16 | def load_checkpoint(self, checkpoint_path):
17 | if os.path.isfile(os.path.join(checkpoint_path, "model_state.pth")):
18 | try:
19 | if self.model.is_cuda:
20 | self.model.load_state_dict(torch.load(os.path.join(checkpoint_path, "model_state.pth")))
21 | else:
22 | self.model.load_state_dict(torch.load(os.path.join(checkpoint_path, "model_state.pth"), map_location="cpu"))
23 | except:
24 | print("Could not load previous model; starting from scratch")
25 | else:
26 | print("No previous model; starting from scratch")
27 |
28 | def save_checkpoint(self, epoch, checkpoint_path):
29 | try:
30 | torch.save(self.model.state_dict(), os.path.join(checkpoint_path, "model_state.pth"))
31 | except:
32 | print("Could not save model")
33 |
34 | def train(self, dataset):
35 | train_acc = 0
36 | train_loss = 0
37 | num_samples = 0
38 | self.model.train()
39 | print_interval = 1000
40 | for idx, batch in enumerate(tqdm(dataset.loader)):
41 | x,T = batch
42 | batch_size = len(x)
43 | num_samples += batch_size
44 | log_probs = self.model(x,T)
45 | loss = -log_probs.mean()
46 | self.optimizer.zero_grad()
47 | loss.backward()
48 | self.optimizer.step()
49 | train_loss += loss.cpu().data.numpy().item() * batch_size
50 | if idx % print_interval == 0:
51 | print(loss.item())
52 | for _ in range(5):
53 | sampled_x, sampled_z = self.model.sample()
54 | print("".join([self.config.Sx[s] for s in sampled_x]))
55 | print(sampled_z)
56 | train_loss /= num_samples
57 | train_acc /= num_samples
58 | return train_loss
59 |
60 | def test(self, dataset, print_interval=20):
61 | test_acc = 0
62 | test_loss = 0
63 | num_samples = 0
64 | self.model.eval()
65 | print_interval = 1000
66 | for idx, batch in enumerate(dataset.loader):
67 | x,T = batch
68 | batch_size = len(x)
69 | num_samples += batch_size
70 | log_probs = self.model(x,T)
71 | loss = -log_probs.mean()
72 | test_loss += loss.cpu().data.numpy().item() * batch_size
73 | if idx % print_interval == 0:
74 | print(loss.item())
75 | sampled_x, sampled_z = self.model.sample()
76 | print("".join([self.config.Sx[s] for s in sampled_x]))
77 | print(sampled_z)
78 | test_loss /= num_samples
79 | test_acc /= num_samples
80 | self.scheduler.step(test_loss) # if the validation loss hasn't decreased, lower the learning rate
81 | return test_loss
82 |
83 |
--------------------------------------------------------------------------------