exercise-variational-mean-field-approximation-for-a-simple-gaussian.ipynb 10.3 KB
 Klaus Strohmenger committed Dec 03, 2018 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 { "cells": [ { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "# Exercise - Variational Mean Field Approximation for Univariate Gaussian" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "## Table of Contents\n", "* [Introduction](#Introduction)\n", "* [Requirements](#Requirements) \n", " * [Knowledge](#Knowledge)\n", " * [Modules](#Python-Modules)\n", "* [Data](#Data)\n", "* [Exercises](#Exercises)\n", " * [Exercise - Mean Field Approximation of the Posterior](Exercise---Mean-Field-Approximation-of-the-Posterior)\n", " * [Exercise - Proof](#Proof)\n", " * [Exercise - Implementation of the Mean Field Approximation](#Exercise---Implementation-of-the-Mean-Field-Approximation)\n", "* [Literature](#Literature)\n", "* [Licenses](#Licenses)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "## Introduction\n", "\n", "**[TODO]**\n", "\n", "In order to detect errors in your own code, execute the notebook cells containing assert or assert_almost_equal." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "## Requirements\n", "\n", "### Knowledge\n", "\n", "**[TODO]**" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "### Python Modules" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", "import numpy as np\n", "from matplotlib import pyplot as plt\n", "import scipy.stats" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.random.seed(40)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Data\n", "\n", "Data:\n", "$$\n", " X \\sim \\mathcal N(\\mu, \\frac{1}{\\tau})\n", "$$\n", "\n", "\n", "Probability Density Function:\n", "$$\n", "p(X \\mid \\mu, \\tau) = \\sqrt{\\frac{\\tau}{2\\pi}} \\exp\\left( -\\frac{\\tau (X-\\mu)^2 }{2} \\right)\n", "$$\n", "\n", "with \n", "- $\\mu$: mean\n", "- $\\sigma^2$: variance\n", "- $\\tau =\\frac{1}{\\sigma^2}$ : precision" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# generation of observed data\n", "N = 10\n", "mu = 10.\n", "sigma = 2.\n", "X = np.random.normal(mu, sigma, N)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = np.arange(3,18,0.01)\n", "p_x = scipy.stats.norm.pdf(x, loc=mu, scale=sigma)\n", "plt.plot(x, p_x, label=\"true Gaussian\")\n", "plt.plot(X, np.zeros_like(X), \"ro\", label=\"Data\")\n", "plt.title(\"\")\n", "plt.xlabel(\"x\")\n", "plt.ylabel(\"p(x)\")\n", "plt.legend();" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercises\n", "\n", "### Exercise - Mean Field Approximation of the Posterior\n", "\n", "**Task:**\n", "\n", "Find the mean field approximation of the posterior:\n", "\n", " $p(\\mu, \\tau \\mid X) \\approx q(\\mu)q(\\tau)$.\n", "\n", "- The observed data was sampled from a Gaussian distribution: $X \\sim \\mathcal N(\\mu, \\frac{1}{\\tau})$.\n", "- Use a constant prior for the mean and the precision $\\tau = \\frac{1}{\\sigma^2}$:\n", "$$\n", "p(\\mu, \\tau) = const. \\quad \\text{ for } \\tau > 0 \n", "$$\n", "\n",  Klaus Strohmenger committed Apr 02, 2019 170 171 172 173  "$\\theta = (\\theta_0, \\theta_1) = (\\mu, \\tau)$\n", "\n", "Note: Typically the mean-field approximation in closed form is done with the conjugate distributions. But here we use\n", "the constant (improper) prior because it's a little bit easier. "  Klaus Strohmenger committed Dec 03, 2018 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249  ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "#### Recap: Mean field approximation\n", "\n", "Loop until convergence:\n", "$$\n", "\\log q({\\theta}_k) = \\mathbb E_{q_{-k}} \\left[ \\log{\\hat p( {\\theta} \\mid {\\mathcal D} )} \\right] + const.\n", "$$" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "**Hint:**\n", "\n", "Use the \"Sum of difference of the mean\":\n", "$$\n", "\\sum_{i=1}^n (x_i-\\mu)^2 = \\sum_{i=1}^n(x_i-\\bar{x})^2 + n(\\bar{x} -\\mu)^2\n", "$$\n", "with\n", "$$\\bar{x} = \\frac{1}{n}\\sum_{i=1}^n x_i$$\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise - Proof\n", "\n", "**Task:**\n", "\n", "Show that:\n", "$$\n", "q(\\mu) = \\mathcal N(\\bar{X}, \\frac{1}{\\gamma_1})\n", "$$\n", "with $\\gamma_1 = m \\mathbb E_{q_{\\tau}}[\\tau]$\n", "\n", "and\n", "\n", "$$\n", "q(\\tau) = \\text{Gamma}(\\frac{m}{2}+1, \\frac{2}{\\gamma_2})\n", "$$\n", "\n", "with \n", "$$\n", "\\gamma_2= \\sum_{i=1}^m \\left(X_i^2\\right)-m\\bar X^2 + m\\text{var}_{q_{\\mu}}(\\mu)\n", "$$" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "#### Gamma distribution\n", "$$\n", "\\text{Gamma}(k, \\theta') = p(x) = x^{k-1}\\frac{e^{-x/\\theta'}}{\\theta'^k\\Gamma(k)}\n", "$$\n", "- $k$ is the shape \n", "- $\\theta'$ the scale, \n",  Klaus Strohmenger committed Apr 02, 2019 250  "- $\\Gamma(.)$ is the Gamma function"  Klaus Strohmenger committed Dec 03, 2018 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390  ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise - Implementation of the Mean Field Approximation \n", "\n", "**Task:**\n", "\n", "Implement the mean field approximation. Like always, you are free to implement as many helper functions as you want.\n", "\n", "If everything is correct, executing the cells below should plot figures similar to these:\n", "\n", "\n", "\n", "" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "def optim(X=X, mean_mu=1, sigma_quare_mu=1, loc_tau=1., scale_tau=1.):\n", " raise NotImplementedError()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mean_mu, sigma_quare_mu, loc_tau, scale_tau = optim(X)\n", "mean_mu, sigma_quare_mu, loc_tau, scale_tau" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.figure(figsize=(12,4))\n", "\n", "x = np.arange(5,15,0.01)\n", "p_mu = scipy.stats.norm.pdf(x, loc=mean_mu, scale=np.sqrt(sigma_quare_mu))\n", "ax = plt.subplot(121)\n", "ax.plot(x, p_mu)\n", "ax.set_xlabel(\"$\\mu$\")\n", "ax.set_ylabel(\"q($\\mu$)\")\n", "ax.set_title(\"Mean: q($\\\\mu$)\")\n", "print(\"true mu: \", mu)\n", "\n", "x = np.arange(0,1,0.01)\n", "p_tau = scipy.stats.gamma.pdf(x, a=loc_tau, scale=scale_tau)\n", "ax = plt.subplot(122)\n", "ax.plot(x, p_tau)\n", "ax.set_xlabel(\"$\\\\tau$\")\n", "ax.set_ylabel(\"q($\\\\tau$)\")\n", "ax.set_title(\"Precision: q($\\\\tau$)\")\n", "print(\"true tau: \", 1/sigma**2)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "## Literature\n", "\n", "**[TODO]**" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "## Licenses\n", "\n", "### Notebook License (CC-BY-SA 4.0)\n", "\n", "*The following license applies to the complete notebook, including code cells. It does however not apply to any referenced external media (e.g., images).*\n", "\n", "Exercise - Variational Mean Field Approximation for Univariate Gaussian
\n", "Based on a work at https://gitlab.com/deep.TEACHING.\n", "\n", "\n", "### Code License (MIT)\n", "\n", "*The following license only applies to code cells of the notebook.*\n", "\n", "Copyright 2018 Christian Herta\n", "\n", "Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n", "\n", "The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n", "\n", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE." ] } ], "metadata": { "celltoolbar": "Slideshow", "kernelspec": { "display_name": "deep_teaching_kernel", "language": "python", "name": "deep_teaching_kernel" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.5" } }, "nbformat": 4, "nbformat_minor": 2 }