Example #1
0
    def _fit_stan_model(self, vb: bool, sm: StanModel, data_dict: Dict,
                        pars: List, gen_init: Union[str, Callable],
                        nchain: int, niter: int, nwarmup: int, nthin: int,
                        adapt_delta: float, stepsize: float,
                        max_treedepth: int, ncore: int) -> Any:
        """Fit the stan model.

        Parameters
        ----------
        vb
            Whether to perform variational Bayesian analysis.
        sm
            The StanModel object to use to fit the model.
        data_dict
            Dict holding the data to pass to Stan.
        pars
            List specifying the parameters of interest.
        gen_init
            String or function to specify how to generate the initial values.
        nchain
            Number of chains to run.
        niter
            Number of iterations per chain.
        nwarmup
            Number of warm-up iterations.
        nthin
            Use every `i == nthin` sample to generate posterior distribution.
        adapt_delta
            Advanced control argument for sampler.
        stepsize
            Advanced control argument for sampler.
        max_treedepth
            Advanced control argument for sampler.
        ncore
            Argument for parallel computing while sampling multiple chains.

        Returns
        -------
        fit
            The fitted result returned by `vb` or `sampling` function.
        """
        if vb:
            return sm.vb(data=data_dict, pars=pars, init=gen_init)
        else:
            return sm.sampling(data=data_dict,
                               pars=pars,
                               init=gen_init,
                               chains=nchain,
                               iter=niter,
                               warmup=nwarmup,
                               thin=nthin,
                               control={
                                   'adapt_delta': adapt_delta,
                                   'stepsize': stepsize,
                                   'max_treedepth': max_treedepth
                               },
                               n_jobs=ncore)
Example #2
0
import pandas as pd
from pystan import StanModel
import matplotlib.pyplot as plt
import pickle

d = pd.read_csv('input/data-attendance-1.txt')
d.Score /= 200
data = d.to_dict('list')
data.update({'N':len(d)})

stanmodel = StanModel(file='model/model5-3.stan')

# NUTS (No U-Turn Sampler)
fit_nuts = stanmodel.sampling(data=data, n_jobs=1)
mcmc_sample = fit_nuts.extract()
mu_est = mcmc_sample['mu']

# ADVI (Automatic Differentiation Variational Inference)
fit_vb = stanmodel.vb(data=data)
vb_sample = pd.read_csv(fit_vb['args']['sample_file'].decode('utf-8'), comment='#')
vb_sample = vb_sample.drop([0,1])
mu_est = vb_sample.filter(regex='mu\.\d+')

with open('output/model_and_result.pkl', 'wb') as f:
    pickle.dump(stanmodel, f)
    pickle.dump(fit_nuts, f)
	}

	X ~ grg(r,N);
}

generated quantities{
	real log_lik;
	//likelihood eval

	log_lik = grg_lpdf(X|r,N);
}
"""

#Inference
#fit = pystan.stan(model_code = stan_code, data = data, iter=1000, chains = 4, n_jobs=1, verbose = False);

#log_lik = fit.extract('log_lik')['log_lik'];

m = StanModel(model_code=stan_code)
fit = m.vb(data=data)
#print fit.keys();

print "log-likelihood:", fit['mean_pars'][-1]

#log_lik = functions['log_lik'];
#print "log-likelihood:", np.mean(log_lik);

#print(fit['args']['sample_file'])

#print "log-likelihood:", np.mean(log_lik);