# 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

[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 = 100
mu = 10.
y = np.random.normal(mu, 2, N)


• 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 = 6
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, fixed=True))

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))

# 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$

• 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');

## Literature

http://people.duke.edu/~ccc14/sta-663/PyMC2.html

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