# Dependent density regression¶

In another example, we showed how to use Dirichlet processes to perform Bayesian nonparametric density estimation. This example expands on the previous one, illustrating dependent density regression.

Just as Dirichlet process mixtures can be thought of as infinite mixture models that select the number of active components as part of inference, dependent density regression can be thought of as infinite mixtures of experts that select the active experts as part of inference. Their flexibility and modularity make them powerful tools for performing nonparametric Bayesian Data analysis.

[1]:

import arviz as az
import numpy as np
import pandas as pd
import pymc3 as pm
import seaborn as sns

from IPython.display import HTML
from matplotlib import animation as ani
from matplotlib import pyplot as plt
from theano import shared
from theano import tensor as tt

print(f"Running on PyMC3 v{pm.__version__}")

/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from float to np.floating is deprecated. In future, it will be treated as np.float64 == np.dtype(float).type.
from ._conv import register_converters as _register_converters

Running on PyMC3 v3.4.1

[2]:

%config InlineBackend.figure_format = 'retina'
plt.rc("animation", writer="ffmpeg")
blue, *_ = sns.color_palette()
az.style.use("arviz-darkgrid")
SEED = 972915  # from random.org; for reproducibility
np.random.seed(SEED)


We will use the LIDAR data set from Larry Wasserman’s excellent book, All of Nonparametric Statistics. We standardize the data set to improve the rate of convergence of our samples.

[4]:

DATA_URI = "http://www.stat.cmu.edu/~larry/all-of-nonpar/=data/lidar.dat"

def standardize(x):
return (x - x.mean()) / x.std()

df = pd.read_csv(DATA_URI, sep=" *", engine="python").assign(
std_range=lambda df: standardize(df.range), std_logratio=lambda df: standardize(df.logratio)
)

/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pandas/io/parsers.py:2218: FutureWarning: split() requires a non-empty pattern match.
yield pat.split(line.strip())
/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pandas/io/parsers.py:2220: FutureWarning: split() requires a non-empty pattern match.
yield pat.split(line.strip())

[5]:

df.head()

[5]:

range logratio std_logratio std_range
0 390 -0.050356 0.852467 -1.717725
1 391 -0.060097 0.817981 -1.707299
2 393 -0.041901 0.882398 -1.686447
3 394 -0.050985 0.850240 -1.676020
4 396 -0.059913 0.818631 -1.655168

We plot the LIDAR data below.

[6]:

fig, ax = plt.subplots(figsize=(8, 6))

ax.scatter(df.std_range, df.std_logratio, c=blue)

ax.set_xticklabels([])
ax.set_xlabel("Standardized range")

ax.set_yticklabels([])
ax.set_ylabel("Standardized log ratio");


This data set has a two interesting properties that make it useful for illustrating dependent density regression.

1. The relationship between range and log ratio is nonlinear, but has locally linear components.

2. The observation noise is heteroskedastic; that is, the magnitude of the variance varies with the range.

The intuitive idea behind dependent density regression is to reduce the problem to many (related) density estimates, conditioned on fixed values of the predictors. The following animation illustrates this intuition.

[7]:

fig, (scatter_ax, hist_ax) = plt.subplots(ncols=2, figsize=(16, 6))

scatter_ax.scatter(df.std_range, df.std_logratio, c=blue, zorder=2)

scatter_ax.set_xticklabels([])
scatter_ax.set_xlabel("Standardized range")

scatter_ax.set_yticklabels([])
scatter_ax.set_ylabel("Standardized log ratio")

bins = np.linspace(df.std_range.min(), df.std_range.max(), 25)

hist_ax.hist(df.std_logratio, bins=bins, color="k", lw=0, alpha=0.25, label="All data")

hist_ax.set_xticklabels([])
hist_ax.set_xlabel("Standardized log ratio")

hist_ax.set_yticklabels([])
hist_ax.set_ylabel("Frequency")

hist_ax.legend(loc=2)

endpoints = np.linspace(1.05 * df.std_range.min(), 1.05 * df.std_range.max(), 15)

frame_artists = []

for low, high in zip(endpoints[:-1], endpoints[2:]):
interval = scatter_ax.axvspan(low, high, color="k", alpha=0.5, lw=0, zorder=1)
*_, bars = hist_ax.hist(
df[df.std_range.between(low, high)].std_logratio, bins=bins, color="k", lw=0, alpha=0.5
)

frame_artists.append((interval,) + tuple(bars))

animation = ani.ArtistAnimation(fig, frame_artists, interval=500, repeat_delay=3000, blit=True)
plt.close()
# prevent the intermediate figure from showing

[8]:

HTML(animation.to_html5_video())

[8]:


As we slice the data with a window sliding along the x-axis in the left plot, the empirical distribution of the y-values of the points in the window varies in the right plot. An important aspect of this approach is that the density estimates that correspond to close values of the predictor are similar.

In the previous example, we saw that a Dirichlet process estimates a probability density as a mixture model with infinitely many components. In the case of normal component distributions,

$y \sim \sum_{i = 1}^{\infty} w_i \cdot N(\mu_i, \tau_i^{-1}),$

where the mixture weights, $$w_1, w_2, \ldots$$, are generated by a stick-breaking process.

Dependent density regression generalizes this representation of the Dirichlet process mixture model by allowing the mixture weights and component means to vary conditioned on the value of the predictor, $$x$$. That is,

$y\ |\ x \sim \sum_{i = 1}^{\infty} w_i\ |\ x \cdot N(\mu_i\ |\ x, \tau_i^{-1}).$

In this example, we will follow Chapter 23 of Bayesian Data Analysis and use a probit stick-breaking process to determine the conditional mixture weights, $$w_i\ |\ x$$. The probit stick-breaking process starts by defining

$v_i\ |\ x = \Phi(\alpha_i + \beta_i x),$

where $$\Phi$$ is the cumulative distribution function of the standard normal distribution. We then obtain $$w_i\ |\ x$$ by applying the stick breaking process to $$v_i\ |\ x$$. That is,

$w_i\ |\ x = v_i\ |\ x \cdot \prod_{j = 1}^{i - 1} (1 - v_j\ |\ x).$

For the LIDAR data set, we use independent normal priors $$\alpha_i \sim N(0, 5^2)$$ and $$\beta_i \sim N(0, 5^2)$$. We now express this this model for the conditional mixture weights using pymc3.

[9]:

def norm_cdf(z):
return 0.5 * (1 + tt.erf(z / np.sqrt(2)))

def stick_breaking(v):
return v * tt.concatenate(
[tt.ones_like(v[:, :1]), tt.extra_ops.cumprod(1 - v, axis=1)[:, :-1]], axis=1
)

[10]:

N, _ = df.shape
K = 20

std_range = df.std_range.values[:, np.newaxis]
std_logratio = df.std_logratio.values[:, np.newaxis]

with pm.Model() as model:
alpha = pm.Normal("alpha", 0.0, 5.0, shape=K)
beta = pm.Normal("beta", 0.0, 5.0, shape=K)
v = norm_cdf(alpha + beta * x_lidar)
w = pm.Deterministic("w", stick_breaking(v))

WARNING (theano.gof.cmodule): The same cache key is associated to different modules (/Users/jlao/.theano/compiledir_Darwin-17.5.0-x86_64-i386-64bit-i386-3.5.1-64/tmp6mq4zwxw and /Users/jlao/.theano/compiledir_Darwin-17.5.0-x86_64-i386-64bit-i386-3.5.1-64/tmprc22erpn). This is not supposed to happen! You may need to manually delete your cache directory to fix this.
WARNING (theano.gof.cmodule): The same cache key is associated to different modules (/Users/jlao/.theano/compiledir_Darwin-17.5.0-x86_64-i386-64bit-i386-3.5.1-64/tmp6mq4zwxw and /Users/jlao/.theano/compiledir_Darwin-17.5.0-x86_64-i386-64bit-i386-3.5.1-64/tmprc22erpn). This is not supposed to happen! You may need to manually delete your cache directory to fix this.


We have defined x_lidar as a theano shared <http://deeplearning.net/software/theano/library/compile/shared.html>__ variable in order to use pymc3’s posterior prediction capabilities later.

While the dependent density regression model theoretically has infinitely many components, we must truncate the model to finitely many components (in this case, twenty) in order to express it using pymc3. After sampling from the model, we will verify that truncation did not unduly influence our results.

Since the LIDAR data seems to have several linear components, we use the linear models

\begin{split}\begin{align*} \mu_i\ |\ x & \sim \gamma_i + \delta_i x \\ \gamma_i & \sim N(0, 10^2) \\ \delta_i & \sim N(0, 10^2) \end{align*}\end{split}

for the conditional component means.

[11]:

with model:
gamma = pm.Normal("gamma", 0.0, 10.0, shape=K)
delta = pm.Normal("delta", 0.0, 10.0, shape=K)
mu = pm.Deterministic("mu", gamma + delta * x_lidar)


Finally, we place the prior $$\tau_i \sim \textrm{Gamma}(1, 1)$$ on the component precisions.

[12]:

with model:
tau = pm.Gamma("tau", 1.0, 1.0, shape=K)
obs = pm.NormalMixture("obs", w, mu, tau=tau, observed=std_logratio)


We now sample from the dependent density regression model.

[13]:

SAMPLES = 20000
BURN = 10000

with model:
step = pm.Metropolis()
trace = pm.sample(SAMPLES, step, chains=1, tune=BURN, random_seed=SEED)

Sequential sampling (1 chains in 1 job)
CompoundStep
>Metropolis: [tau]
>Metropolis: [delta]
>Metropolis: [gamma]
>Metropolis: [beta]
>Metropolis: [alpha]
100%|██████████| 30000/30000 [02:44<00:00, 182.90it/s]
Only one chain was sampled, this makes it impossible to run some convergence checks


To verify that truncation did not unduly influence our results, we plot the largest posterior expected mixture weight for each component. (In this model, each point has a mixture weight for each component, so we plot the maximum mixture weight for each component across all data points in order to judge if the component exerts any influence on the posterior.)

[14]:

fig, ax = plt.subplots(figsize=(8, 6))

ax.bar(np.arange(K) + 1, trace["w"].mean(axis=0).max(axis=0))

ax.set_xlim(1 - 0.5, K + 0.5)
ax.set_xticks(np.arange(0, K, 2) + 1)
ax.set_xlabel("Mixture component")

ax.set_ylabel("Largest posterior expected\nmixture weight");


Since only three mixture components have appreciable posterior expected weight for any data point, we can be fairly certain that truncation did not unduly influence our results. (If most components had appreciable posterior expected weight, truncation may have influenced the results, and we would have increased the number of components and sampled again.)

Visually, it is reasonable that the LIDAR data has three linear components, so these posterior expected weights seem to have identified the structure of the data well. We now sample from the posterior predictive distribution to get a better understand the model’s performance.

[15]:

PP_SAMPLES = 5000

lidar_pp_x = np.linspace(std_range.min() - 0.05, std_range.max() + 0.05, 100)
x_lidar.set_value(lidar_pp_x[:, np.newaxis])

with model:
pp_trace = pm.sample_posterior_predictive(trace, PP_SAMPLES, random_seed=SEED)

100%|██████████| 5000/5000 [00:33<00:00, 151.39it/s]


Below we plot the posterior expected value and the 95% posterior credible interval.

[18]:

fig, ax = plt.subplots(figsize=(8, 6))

ax.scatter(df.std_range, df.std_logratio, c=blue, zorder=10, label=None)

low, high = np.percentile(pp_trace["obs"], [2.5, 97.5], axis=0)
ax.fill_between(
lidar_pp_x, low, high, color="k", alpha=0.35, zorder=5, label="95% posterior credible interval"
)

ax.plot(lidar_pp_x, pp_trace["obs"].mean(axis=0), c="k", zorder=6, label="Posterior expected value")

ax.set_xticklabels([])
ax.set_xlabel("Standardized range")

ax.set_yticklabels([])
ax.set_ylabel("Standardized log ratio")

ax.legend(loc=1)
ax.set_title("LIDAR Data");


The model has fit the linear components of the data well, and also accomodated its heteroskedasticity. This flexibility, along with the ability to modularly specify the conditional mixture weights and conditional component densities, makes dependent density regression an extremely useful nonparametric Bayesian model.

To learn more about depdendent density regression and related models, consult Bayesian Data Analysis, Bayesian Nonparametric Data Analysis, or Bayesian Nonparametrics.

This example first appeared here.

Author: Austin Rochford

[25]:

%load_ext watermark
%watermark -n -u -v -iv -w

arviz  0.8.3
pymc3  3.8
pandas 1.0.3
numpy  1.18.1
last updated: Wed Jun 10 2020

CPython 3.6.10
IPython 7.13.0
watermark 2.0.2
{"extraction_info": {"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 1, "mathjax_display_tex": 1, "mathjax_asciimath": 1, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "math_score": 0.8881696462631226, "perplexity": 5997.045752652156}, "config": {"markdown_headings": true, "markdown_code": true, "boilerplate_config": {"ratio_threshold": 0.18, "absolute_threshold": 10, "end_threshold": 15, "enable": true}, "remove_buttons": true, "remove_image_figures": true, "remove_link_clusters": true, "table_config": {"min_rows": 2, "min_cols": 3, "format": "plain"}, "remove_chinese": true, "remove_edit_buttons": true, "extract_latex": true}, "warc_path": "s3://commoncrawl/crawl-data/CC-MAIN-2021-04/segments/1610704799711.94/warc/CC-MAIN-20210126073722-20210126103722-00365.warc.gz"}