# What is this model

H=hits \sim Bin(AB=at\ bats, AVG=p)\\ AVG=p \sim Beta(\alpha, \beta)\\ E[p] = \frac{\alpha}{\alpha+\beta} = \mu\\ \mu = \beta_0+\beta_1*lnAB+\beta_2*bats
Which the bats means handedness.

# Code

text=‘’’
data{
int<lower=0> N;
int<lower=0> AB[N];
real logAB[N];
int<lower=0> H[N];
int<lower=0, upper=1> bat[N];
}
parameters{
real beta0;
real beta1;
real beta2;
real sigma;
}
transformed parameters{
vector[N] mu_i;
vector[N] alpha_i;
vector[N] beta_i;
mu_i = beta0 + to_vector(logAB)*beta1 + to_vector(bat)*beta2;
alpha_i = mu_i/sigma;
beta_i = (1-mu_i)/sigma;
}
model{
beta0~normal(0,1);
beta1~normal(0,1);
beta2~normal(0,1);
sigma~normal(0,1);
H~beta_binomial(AB, alpha_i, beta_i);
}
stan_data = {‘N’:4245, ‘AB’:list(career_name2[‘AB’].astype(int)), ‘logAB’: list(logAB), ‘H’: list(career_name2[‘H’].astype(int)), ‘bat’: list(bats.astype(int))}
posterior = stan.build(text, data=stan_data)
fit = posterior.sample(num_chains=1, num_samples=1000)
df_hier = fit.to_frame()

## So basically it’s a betabinomial model, with the expectation mu is associated with ln(AB) and bats, a boolean variable. The problem is that this code worked at first try, but after I revised other parts(e.g. generating data part), it crashed. I pasted the error messsage below. Error message Building: found in cache, done.Sampling: 0%CRITICAL:httpstan:Exception during call to services function: ValueError('Initialization failed.'), traceback: [' File "/usr/lib/python3.7/asyncio/tasks.py", line 249, in __step\n result = coro.send(None)\n', ' File "/usr/local/lib/python3.7/dist-packages/httpstan/services_stub.py", line 160, in call\n future.result()\n', ' File "/usr/lib/python3.7/asyncio/futures.py", line 181, in result\n raise self._exception\n', ' File "/usr/lib/python3.7/concurrent/futures/process.py", line 239, in _process_worker\n r = call_item.fn(*call_item.args, **call_item.kwargs)\n', ' File "/usr/local/lib/python3.7/dist-packages/httpstan/services_stub.py", line 47, in _make_lazy_function_wrapper_helper\n return function(*args, **kwargs) # type: ignore\n'] Sampling: Initialization failed.

RuntimeError Traceback (most recent call last)
in
1 stan_data = {‘N’:4245, ‘AB’:list(career_name2[‘AB’].astype(int)), ‘logAB’: list(logAB), ‘H’: list(career_name2[‘H’].astype(int)), ‘bat’: list(bats.astype(int))}
2 posterior = stan.build(text, data=stan_data)
----> 3 fit = posterior.sample(num_chains=1, num_samples=1000)
4 df_hier = fit.to_frame()

Unfortunetly, I have already check my data and they were all inside the given range, so I don’t know how to deal with it

I think alpha_i and beta_i needs to be positive, so add constrains for your parameters

Thanks a lot!
It works.