Created
April 16, 2021 16:09
-
-
Save shaabhishek/a1fdbc3896d69afdd50f147fbd8ae436 to your computer and use it in GitHub Desktop.
CmdStanPy on Colab Starter Code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
########### INSTALL ########### | |
# !pip install --upgrade cmdstanpy | |
import os | |
import urllib.request | |
import shutil | |
# Install pre-built CmdStan binary | |
# (faster than compiling from source via install_cmdstan() function) | |
tgz_file = 'colab-cmdstan-2.23.0.tar.gz' | |
tgz_url = 'https://github.com/stan-dev/cmdstan/releases/download/v2.23.0/colab-cmdstan-2.23.0.tar.gz' | |
if not os.path.exists(tgz_file): | |
urllib.request.urlretrieve(tgz_url, tgz_file) | |
shutil.unpack_archive(tgz_file) | |
# # Specify CmdStan location via environment variable | |
os.environ['CMDSTAN'] = './cmdstan-2.23.0' | |
# # Check CmdStan path | |
from cmdstanpy import CmdStanModel, cmdstan_path | |
print(cmdstan_path()) | |
########### LOAD MODEL FILE AND SETUP DATA ########### | |
model_data = { | |
"N": 35303, | |
"K": 7, | |
"P": 2, | |
"y": profit_data['y'].values, | |
"ITT": profit_data['T'].values, | |
"site": profit_data['k'].values, | |
"mutau_prior_mean": np.zeros(2), | |
"mutau_prior_sigma": np.eye(2)*1e6, | |
} | |
model = CmdStanModel(stan_file='/content/drive/MyDrive/MIT6.435/project/basic-microcredit-uninformative-ss.stan') | |
# Need to run this command if the model is already compiled and loaded from file | |
# Otherwise the inference step throws an error for me | |
#!chmod 755 '/content/drive/MyDrive/MIT6.435/project/basic-microcredit-uninformative-ss' | |
########### GENERATE SAMPLES ########### | |
fit = model.sample(data=model_data, iter_sampling=10000, cores=2, output_dir='/content/drive/MyDrive/MIT6.435/project') | |
# fit.summary() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment