Skip to content

Commit d4b95b7

Browse files
committed
added notebook, files
1 parent 5612b10 commit d4b95b7

4 files changed

Lines changed: 203 additions & 1 deletion

File tree

cmdstanpy/stanfit.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2098,7 +2098,7 @@ def column_names(self) -> Tuple[str, ...]:
20982098
@property
20992099
def eta(self) -> float:
21002100
"""
2101-
Adapted value of step size 'eta'
2101+
Step size scaling parameter 'eta'
21022102
"""
21032103
return self._eta
21042104

Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"metadata": {},
6+
"source": [
7+
"## Using Variational Estimates to Initialize the NUTS-HMC Sampler\n",
8+
"\n",
9+
"In this example we show how to use the parameter estimates return by Stan's variational inference algorithm\n",
10+
"as the initial parameter values for Stan's NUTS-HMC sampler, using a the [earnings-logearn_height model](https://github.com/stan-dev/posteriordb/blob/master/posterior_database/models/stan/logearn_height.stan) and data from the [posteriordb package](https://github.com/stan-dev/posteriordb).\n",
11+
"\n",
12+
"The experiments reported in the paper [Pathfinder: Parallel quasi-Newton variational inference](https://arxiv.org/abs/2108.03782) by Zhang et al. show that mean-field ADVI provides a better estimate of the posterior, as measured by the 1-Wasserstein distance to the reference posterior, than 75 iterations of the warmup Phase I algorithm used by the NUTS-HMC sampler, furthermore, ADVI is more computationally efficient, requiring fewer evaluations of the log density and gradient functions. Therefore, using the estimates from ADVI to initialize the parameter values for the NUTS-HMC sampler will allow the sampler to do a better job of adapting the stepsize and metric during warmup, resulting in better performance and estimation.\n",
13+
"\n",
14+
"\n",
15+
"### Model and data\n",
16+
"\n",
17+
"For conveince, we have copied the posteriordb model and data to this directory, in files [logearn_height.stan](logearn_height.stan) and [earnings.json](earnings.json)."
18+
]
19+
},
20+
{
21+
"cell_type": "code",
22+
"execution_count": null,
23+
"metadata": {},
24+
"outputs": [],
25+
"source": [
26+
"import os\n",
27+
"from cmdstanpy import CmdStanModel\n",
28+
" \n",
29+
"stan_file = 'logearn_height.stan'\n",
30+
"data_file = 'earnings.json'\n",
31+
"\n",
32+
"# instantiate, compile bernoulli model\n",
33+
"model = CmdStanModel(stan_file=stan_file)"
34+
]
35+
},
36+
{
37+
"cell_type": "markdown",
38+
"metadata": {},
39+
"source": [
40+
"### Run Stan's variational inference algorithm, obtain fitted estimates\n",
41+
"\n",
42+
"The `CmdStanModel` method `variational` runs CmdStan's ADVI algorithm.\n",
43+
"Conditioning the model on the data results in a posterior geometry which is difficult to navigate. Because the ADVI algorithm may fail to converge, we run it with argument `require_converged` set to `False`."
44+
]
45+
},
46+
{
47+
"cell_type": "code",
48+
"execution_count": null,
49+
"metadata": {},
50+
"outputs": [],
51+
"source": [
52+
"vb_fit = model.variational(data=data_file, require_converged=False, seed=123)"
53+
]
54+
},
55+
{
56+
"cell_type": "markdown",
57+
"metadata": {},
58+
"source": [
59+
"The ADVI algorithm provides estimates of all model parameters as well as the step size scaling factor `eta`.\n",
60+
"\n",
61+
"The `variational` method returns a `CmdStanVB` object, with methods `eta` and `stan_variables`, which\n",
62+
"return the step size scaling factor and estimates of all model parameters as a Python dictionary respectively."
63+
]
64+
},
65+
{
66+
"cell_type": "code",
67+
"execution_count": null,
68+
"metadata": {},
69+
"outputs": [],
70+
"source": [
71+
"print(vb_fit.eta, vb_fit.stan_variables())"
72+
]
73+
},
74+
{
75+
"cell_type": "markdown",
76+
"metadata": {},
77+
"source": [
78+
"Posteriordb provides reference posteriors for all models. For the logearn_height model, conditioned on the dataset `earnings.json`, the posterior variables are:\n",
79+
"\n",
80+
"- beta[1]: 5.782\n",
81+
"- beta[2]: 0.059\n",
82+
"- sigma: 0.894\n",
83+
"\n",
84+
"By default, the sampler algorithm randomly initializes all model parameters in the range uniform[-2, 2]. The ADVI estimates will provide a better starting point, especially w/r/t to parameter `beta[1]`, than the defaults.\n",
85+
"In addition, we can use the step size scaling factor to scale the initial step size, which allows us to skip the first phase of warmup (default 75 iterations)."
86+
]
87+
},
88+
{
89+
"cell_type": "code",
90+
"execution_count": null,
91+
"metadata": {},
92+
"outputs": [],
93+
"source": [
94+
"vb_vars = vb_fit.stan_variables()\n",
95+
"vb_stepsize = 1.0 / vb_fit.eta\n",
96+
"mcmc_vb_inits_fit = model.sample(\n",
97+
" data=data_file, inits=vb_vars, step_size=vb_stepsize,\n",
98+
" adapt_init_phase=0, seed=123\n",
99+
")"
100+
]
101+
},
102+
{
103+
"cell_type": "code",
104+
"execution_count": null,
105+
"metadata": {},
106+
"outputs": [],
107+
"source": [
108+
"mcmc_vb_inits_fit.summary()"
109+
]
110+
},
111+
{
112+
"cell_type": "markdown",
113+
"metadata": {},
114+
"source": [
115+
"The sampler results match the reference posterior, (taking into account MCSE).\n",
116+
"\n",
117+
"- beta[1]: 5.782\n",
118+
"- beta[2]: 0.059\n",
119+
"- sigma: 0.894\n",
120+
"\n",
121+
"To see how this is useful, we run the sampler with default initializations, step size, and warmup, (same random seed)."
122+
]
123+
},
124+
{
125+
"cell_type": "code",
126+
"execution_count": null,
127+
"metadata": {},
128+
"outputs": [],
129+
"source": [
130+
"mcmc_random_inits_fit = model.sample(data=data_file, seed=123)"
131+
]
132+
},
133+
{
134+
"cell_type": "code",
135+
"execution_count": null,
136+
"metadata": {},
137+
"outputs": [],
138+
"source": [
139+
"mcmc_random_inits_fit.summary()"
140+
]
141+
},
142+
{
143+
"cell_type": "markdown",
144+
"metadata": {},
145+
"source": [
146+
"On my machine, using the variational estimates to skip warmup phase I shows improved **N_EFF/s** values for all parameters.\n",
147+
"\n",
148+
"This is a simple model run on a small dataset. For complex models where the initial parameter values are far from the default initializations, this procedure may allow for faster and better adaptation during warmup."
149+
]
150+
},
151+
{
152+
"cell_type": "code",
153+
"execution_count": null,
154+
"metadata": {},
155+
"outputs": [],
156+
"source": []
157+
}
158+
],
159+
"metadata": {
160+
"kernelspec": {
161+
"display_name": "Python 3",
162+
"language": "python",
163+
"name": "python3"
164+
},
165+
"language_info": {
166+
"codemirror_mode": {
167+
"name": "ipython",
168+
"version": 3
169+
},
170+
"file_extension": ".py",
171+
"mimetype": "text/x-python",
172+
"name": "python",
173+
"nbconvert_exporter": "python",
174+
"pygments_lexer": "ipython3",
175+
"version": "3.8.5"
176+
}
177+
},
178+
"nbformat": 4,
179+
"nbformat_minor": 4
180+
}

0 commit comments

Comments
 (0)