Iterative MAP estimation with increasing data points

I am trying to examine how MAP estimates change as number of data increases.
I used for loop to increase the data points monotonically, and used pm.find_MAP to estimate MAP of posterior
Roughly I wrote the code in this way (omitted @as_op part).

basic_model = pm.Model()
est_start = 15       # estimation starting time (referring row number)     
Leff_MAP = np.zeros((len(df_est['T_mean']), ))  
Rb_MAP = np.zeros((len(df_est['T_mean']), ))

for est_end in range(est_start, len(df_est['T_mean'])):
    with basic_model:
        Leff = pm.Normal('Leff', mu=3.0, sd=1.5)
        Rb = pm.Normal('Rb', mu=0.11, sd=0.1) 

        Tf_est_py = ils_super_pymc(q_shared, t_shared, rb_shared, Leff, Cs_shared) + Rb*q + T0
        Y_obs = pm.Normal('Y_obs', mu=Tf_est_py[est_start:est_end], sd=0.7, observed=df_est['T_mean'][est_start:est_end])
    map_estimate = pm.find_MAP(model=basic_model, method="L-BFGS-B")

    Leff_MAP[est_end], Rb_MAP[est_end] = map_estimate['Leff'], map_estimate['Rb']

However, I found out that defining priors with using the same name is not allowed in pyMC3.
Thus, I was faced with this error.

ValueError: Variable name Leff already exists.

Of course there would be another error message for the other prior Rb.
How can I solve this problem?
Is there a way to define priors outside of the with basic_model: statement?
or is there a smarter way to do this?

Thank you in advance.

I answer my question.
Writing the model statement basic_model = pm.Model() inside the for loop made it work.

for est_end in range(est_start, len(df_est[‘T_mean’]):
basic_model = pm.Model()
with basic_model:

you can also do with pm.Model() as basic_model: which can save you 1 line of code :slight_smile:

1 Like