├── .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 | "![Diagram of a traveling friend sending selfies](https://github.com/lorenlugosch/pytorch_HMM/blob/master/img/selfies.png?raw=true)\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 | "![Diagram of an HMM for three timesteps](https://github.com/lorenlugosch/pytorch_HMM/blob/master/img/hmm.png?raw=true)\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))\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 | --------------------------------------------------------------------------------