|
7 | 7 | "## Using Variational Estimates to Initialize the NUTS-HMC Sampler\n", |
8 | 8 | "\n", |
9 | 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", |
| 10 | + "as the initial parameter values for Stan's NUTS-HMC sampler.\n", |
| 11 | + "By default, the sampler algorithm randomly initializes all model parameters in the range uniform\\[-2, 2\\]. When the true parameter value is outside of this range, starting from the ADVI estimates will speed up and improve adaptation.\n", |
14 | 12 | "\n", |
15 | 13 | "### Model and data\n", |
16 | 14 | "\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)." |
| 15 | + "The Stan model and data are taken from the [posteriordb package](https://github.com/stan-dev/posteriordb).\n", |
| 16 | + "\n", |
| 17 | + "We use the [blr model](https://github.com/stan-dev/posteriordb/blob/master/posterior_database/models/stan/blr.stan),\n", |
| 18 | + "a Bayesian standard linear regression model with noninformative priors,\n", |
| 19 | + "and its corresponding simulated dataset [sblri.json](https://github.com/stan-dev/posteriordb/blob/master/posterior_database/data/data/sblri.json.zip),\n", |
| 20 | + "which was simulated via script [sblr.R](https://github.com/stan-dev/posteriordb/blob/master/posterior_database/data/data-raw/sblr/sblr.R).\n", |
| 21 | + "For conveince, we have copied the posteriordb model and data to this directory, in files `blr.stan` and `sblri.json`." |
18 | 22 | ] |
19 | 23 | }, |
20 | 24 | { |
|
25 | 29 | "source": [ |
26 | 30 | "import os\n", |
27 | 31 | "from cmdstanpy import CmdStanModel\n", |
28 | | - " \n", |
29 | | - "stan_file = 'logearn_height.stan'\n", |
30 | | - "data_file = 'earnings.json'\n", |
31 | 32 | "\n", |
32 | | - "# instantiate, compile bernoulli model\n", |
33 | | - "model = CmdStanModel(stan_file=stan_file)" |
| 33 | + "stan_file = 'blr.stan' # basic linear regression\n", |
| 34 | + "data_file = 'sblri.json' # simulated data\n", |
| 35 | + "\n", |
| 36 | + "model = CmdStanModel(stan_file=stan_file)\n", |
| 37 | + "\n", |
| 38 | + "print(model.code())" |
34 | 39 | ] |
35 | 40 | }, |
36 | 41 | { |
37 | 42 | "cell_type": "markdown", |
38 | 43 | "metadata": {}, |
39 | 44 | "source": [ |
40 | | - "The earnings dataset is a set of 1192 observations of annual earnings in USD, height in inches, and indicator for sex==male." |
| 45 | + "### Run Stan's variational inference algorithm, obtain fitted estimates\n", |
| 46 | + "\n", |
| 47 | + "The `CmdStanModel` method `variational` runs CmdStan's ADVI algorithm.\n", |
| 48 | + "Because this algorithm is unstable and may fail to converge, we run it with argument `require_converged` set to `False`. We also specify a seed, to avoid instabilities as well as for reproducibility." |
41 | 49 | ] |
42 | 50 | }, |
43 | 51 | { |
|
46 | 54 | "metadata": {}, |
47 | 55 | "outputs": [], |
48 | 56 | "source": [ |
49 | | - "import json\n", |
50 | | - "with open(data_file, 'r') as fd:\n", |
51 | | - " data_dict = json.load(fd)\n", |
52 | | - "print(data_dict.keys())\n", |
53 | | - "print(data_dict['N'])\n", |
54 | | - "for i in range(5):\n", |
55 | | - " print(data_dict['earn'][i], data_dict['height'][i])\n" |
| 57 | + "vb_fit = model.variational(data=data_file, require_converged=False, seed=123)" |
56 | 58 | ] |
57 | 59 | }, |
58 | 60 | { |
59 | 61 | "cell_type": "markdown", |
60 | 62 | "metadata": {}, |
61 | 63 | "source": [ |
62 | | - "The \"logearn_height\" model regresses the log earnings on height." |
| 64 | + "The ADVI algorithm provides estimates of all model parameters.\n", |
| 65 | + "\n", |
| 66 | + "The `variational` method returns a `CmdStanVB` object, with method `stan_variables`, which\n", |
| 67 | + "returns the approximate estimates of all model parameters as a Python dictionary." |
63 | 68 | ] |
64 | 69 | }, |
65 | 70 | { |
|
68 | 73 | "metadata": {}, |
69 | 74 | "outputs": [], |
70 | 75 | "source": [ |
71 | | - "print(model.code())" |
| 76 | + "print(vb_fit.stan_variables())" |
72 | 77 | ] |
73 | 78 | }, |
74 | 79 | { |
75 | 80 | "cell_type": "markdown", |
76 | 81 | "metadata": {}, |
77 | 82 | "source": [ |
78 | | - "### Run Stan's variational inference algorithm, obtain fitted estimates\n", |
| 83 | + "Posteriordb provides reference posteriors for all models. For the blr model, conditioned on the dataset `sblri.json`, the reference posteriors are in file [sblri-blr.json](https://github.com/stan-dev/posteriordb/blob/master/posterior_database/reference_posteriors/summary_statistics/mean/mean/sblri-blr.json)\n", |
79 | 84 | "\n", |
80 | | - "The `CmdStanModel` method `variational` runs CmdStan's ADVI algorithm.\n", |
81 | | - "Conditioning the model on the data results in a posterior geometry which is difficult to navigate. Because the ADVI algorithm is unstable and may fail to converge, we run it with argument `require_converged` set to `False`. We also specify a seed, to avoid instabilities as well as for reproducibility." |
| 85 | + "The reference posteriors for all elements of `beta` and `sigma` are all very close to $1.0$.\n", |
| 86 | + "\n", |
| 87 | + "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" |
82 | 88 | ] |
83 | 89 | }, |
84 | 90 | { |
|
87 | 93 | "metadata": {}, |
88 | 94 | "outputs": [], |
89 | 95 | "source": [ |
90 | | - "vb_fit = model.variational(data=data_file, require_converged=False, seed=123)" |
91 | | - ] |
92 | | - }, |
93 | | - { |
94 | | - "cell_type": "markdown", |
95 | | - "metadata": {}, |
96 | | - "source": [ |
97 | | - "The ADVI algorithm provides estimates of all model parameters as well as the step size scaling factor `eta`.\n", |
98 | | - "\n", |
99 | | - "The `variational` method returns a `CmdStanVB` object, with methods `eta` and `stan_variables`, which\n", |
100 | | - "return the step size scaling factor and estimates of all model parameters as a Python dictionary respectively." |
| 96 | + "vb_vars = vb_fit.stan_variables()\n", |
| 97 | + "mcmc_vb_inits_fit = model.sample(\n", |
| 98 | + " data=data_file, inits=vb_vars, iter_warmup=75, seed=12345\n", |
| 99 | + ")" |
101 | 100 | ] |
102 | 101 | }, |
103 | 102 | { |
|
106 | 105 | "metadata": {}, |
107 | 106 | "outputs": [], |
108 | 107 | "source": [ |
109 | | - "print(vb_fit.eta, vb_fit.stan_variables())" |
| 108 | + "mcmc_vb_inits_fit.summary()" |
110 | 109 | ] |
111 | 110 | }, |
112 | 111 | { |
113 | 112 | "cell_type": "markdown", |
114 | 113 | "metadata": {}, |
115 | 114 | "source": [ |
116 | | - "Posteriordb provides reference posteriors for all models. For the logearn_height model, conditioned on the dataset `earnings.json`, the posterior variables are:\n", |
117 | | - "\n", |
118 | | - "- beta[1]: 5.782\n", |
119 | | - "- beta[2]: 0.059\n", |
120 | | - "- sigma: 0.894\n", |
121 | | - "\n", |
122 | | - "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", |
123 | | - "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)." |
| 115 | + "The sampler estimates match the reference posterior." |
124 | 116 | ] |
125 | 117 | }, |
126 | 118 | { |
|
129 | 121 | "metadata": {}, |
130 | 122 | "outputs": [], |
131 | 123 | "source": [ |
132 | | - "vb_vars = vb_fit.stan_variables()\n", |
133 | | - "vb_stepsize = 1.0 / vb_fit.eta\n", |
134 | | - "mcmc_vb_inits_fit = model.sample(\n", |
135 | | - " data=data_file, inits=vb_vars, step_size=vb_stepsize,\n", |
136 | | - " adapt_init_phase=0, seed=123\n", |
137 | | - ")" |
138 | | - ] |
139 | | - }, |
140 | | - { |
141 | | - "cell_type": "code", |
142 | | - "execution_count": null, |
143 | | - "metadata": {}, |
144 | | - "outputs": [], |
145 | | - "source": [ |
146 | | - "mcmc_vb_inits_fit.summary()" |
| 124 | + "print(mcmc_vb_inits_fit.diagnose())" |
147 | 125 | ] |
148 | 126 | }, |
149 | 127 | { |
150 | 128 | "cell_type": "markdown", |
151 | 129 | "metadata": {}, |
152 | 130 | "source": [ |
153 | | - "The sampler results match the reference posterior, (taking into account MCSE).\n", |
154 | | - "\n", |
155 | | - "- beta[1]: 5.782\n", |
156 | | - "- beta[2]: 0.059\n", |
157 | | - "- sigma: 0.894\n", |
158 | | - "\n", |
159 | | - "To see how this is useful, we run the sampler with default initializations, step size, and warmup." |
| 131 | + "Using the default random parameter initializations, we need to run more warmup iteratons. If we only run 75 warmup iterations with random inits, the result fails to estimate `sigma` correctly. It is necessary to run the model with at least 150 warmup iterations to produce a good set of estimates." |
160 | 132 | ] |
161 | 133 | }, |
162 | 134 | { |
|
165 | 137 | "metadata": {}, |
166 | 138 | "outputs": [], |
167 | 139 | "source": [ |
168 | | - "mcmc_random_inits_fit = model.sample(data=data_file, seed=123)" |
| 140 | + "mcmc_random_inits_fit = model.sample(data=data_file, iter_warmup=75, seed=12345)" |
169 | 141 | ] |
170 | 142 | }, |
171 | 143 | { |
|
178 | 150 | ] |
179 | 151 | }, |
180 | 152 | { |
181 | | - "cell_type": "markdown", |
| 153 | + "cell_type": "code", |
| 154 | + "execution_count": null, |
182 | 155 | "metadata": {}, |
| 156 | + "outputs": [], |
183 | 157 | "source": [ |
184 | | - "Using the variational estimates to skip warmup phase I shows improved N_Eff/s (number of effective sampler per second) values for all parameters. 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." |
| 158 | + "print(mcmc_random_inits_fit.diagnose())" |
185 | 159 | ] |
186 | 160 | } |
187 | 161 | ], |
|
0 commit comments