Pymc3 Examples

Introduction

[TODO]

Remark: In order to detect errors in your own code, execute the notebook cells containing assert or assert_almost_equal. These statements raise exceptions, as long as the calculated result is not yet correct.

Requirements

Knowledge

[TODO]

Python Modules

import os
import scipy.stats
import scipy.special as sps
import pymc3 as pm
import pandas as pd
import numpy as np
import daft

from IPython.core.pylabtools import figsize
from IPython.display import Image
from matplotlib import pyplot as plt
from matplotlib import rc

#rc("font", family="serif", size=16)

%matplotlib inline

Exercises

Estimating Mean and Standard Deviation of Normal Distribution

Data: $ X \sim \mathcal N(\mu, \sigma^2) $

Probability Density Function: $ f(X \mid \mu, \tau) = \sqrt{\frac{\tau}{2\pi}} \exp\left\{ -\frac{\tau}{2} (X-\mu)^2 \right\} $

with
-$ \mu $: mean -$ \sigma $: standard deviation -$ \sigma^2 $ : variance

  • precision$ \tau := 1/\sigma^2 $

Build the following model

  • The observed data should come from a Gaussian distribution$ \mathcal N(\mu, \sigma^2) $.
  • Use a unifom prior for the mean: unifor$ (-50, 50) $
  • Use a uniform prior for the standard deviation: unifor$ (0.001, 100) $
# generate observed data
N = 10
mu = 10.
y = np.random.normal(mu, 2, N)
y

Task:

  • Use pymc3 to get samples from the posterior for$ \mu $ and$ \sigma $.
  • Plot the sample histograms of$ \mu $ and$ \sigma $.
pm.model_to_graphviz(gaussian_model)
_ = pm.traceplot(trace)

Estimating Parameters of a Linear Regression Model

We will show how to estimate regression parameters using a simple linear model

$ y \sim ax + b $

We can restate the linear model: $ y = ax + b + \epsilon $

as sampling from a probability distribution

$ y \sim \mathcal N(ax + b, \sigma^2) $

Now we can use pymc to estimate the paramters$ a, b $ and$ \sigma $.

e.g. assume the following priors (choose vales for the '?': $ a \sim \mathcal N (?, ?) $ $ b \sim \mathcal N (?, ?) $ $ \tau \sim HalfNormal (?, ?) $

# observed data
n = 3
a = 20
b = 4
sigma = 2.5
x = np.random.uniform(0, 1, n)
y_obs = a*x + b + np.random.normal(0, sigma, n)
data = pd.DataFrame(np.array([x, y_obs]).T, columns=['x', 'y'])
data.plot(x='x', y='y', kind='scatter', s=50)

Graphical Model

def plot_glm():
    pgm = daft.PGM([5.3, 4.05], origin=[-0.3, -0.3], aspect=1.)
    #pgm.add_node(daft.Node("alpha", r"$\alpha$", 2.5, 3, fixed=True))
    pgm.add_node(daft.Node("sigma", r"$\sigma$", 3.5, 2.2))

    pgm.add_node(daft.Node("theta", r"$\theta$", 2.5, 2.2))
    # Data.
    pgm.add_node(daft.Node("xi", r"$\vec x^{(i)}$", 1.5, 1, fixed=True))
    pgm.add_node(daft.Node("yi", r"$y^{(i)}$", 2.5, 1, observed=True))

    pgm.add_node(daft.Node("x", r"$\vec x$", 4.5, 1, fixed=True))
    pgm.add_node(daft.Node("y", r"$y$", 3.5, 1))

    # Add in the edges.
   # pgm.add_edge("alpha", "theta")
    pgm.add_edge("theta", "yi")
    pgm.add_edge("xi", "yi")
    pgm.add_edge("sigma", "yi")

    pgm.add_edge("x", "y")
    pgm.add_edge("theta", "y")
    pgm.add_edge("sigma", "y")
    # And a plate.
    pgm.add_plate(daft.Plate([1., .4, 2, 1.1], label=r"$i = 1, \ldots, n$",
    shift=-0.1))

    pgm.render()
plot_glm()
  • inside the plate are the training data$ \mathcal D = \{(\vec x^{(i)}, y^{(i)})\} $ -$ \vec x $ is not considered as random variable. -$ \theta = \{a, b\} $ is a latent variable -$ y $ is the prediction for an$ \vec x $ -$ \alpha $ are the parameters for the prior of$ a $ and$ b $

Task:

  • Build the model in pymc3
  • Use pymc3 to estimate the paramters$ a, b $ and$ \sigma $.
  • Plot the distribution of the parameters.
  • Optinal: Plot the data with multiple regression lines.
pm.model_to_graphviz(model)
_ = pm.traceplot(trace)
abar = trace.slope.mean() # a
bbar = trace.intercept.mean() # b
data.plot(x='x', y='y', kind='scatter', s=50);
xp = np.array([x.min(), x.max()])
plt.plot(xp, trace.slope*xp[:, None] + trace.intercept, c='red', alpha=.01)
plt.plot(xp, abar*xp[:, None] + bbar, linewidth=2, c='black');

Licenses

Notebook License (CC-BY-SA 4.0)

The following license applies to the complete notebook, including code cells. It does however not apply to any referenced external media (e.g., images).

pymc3 Examples
by Christian Herta, Klaus Strohmenger
is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Based on a work at https://gitlab.com/deep.TEACHING.

Code License (MIT)

The following license only applies to code cells of the notebook.

Copyright 2018 Christian Herta, Klaus Strohmenger

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:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

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.