Please find the code
def bayesian_lin_reg_fit(x_data_shared,y_data_shared,display_plot=True,Intercept=False):
with pm.Model() as linear_model:
sigma = pm.Uniform('Sigma',0,100)
intercept = pm.Uniform('Intercept',0,1200)
x_coeff = pm.Uniform('Slope',-10,10)
if(Intercept==True):
yhat = pm.math.dot(x_data_shared,x_coeff)+intercept
else:
yhat = pm.math.dot(x_data_shared,x_coeff)
#Likelihood
likelihood = pm.Normal('y',yhat,sigma,observed=y_data_shared)
print(likelihood)
#Inference
trace_linear = pm.sample(500,cores=1,init="auto",tune=500,progressbar=True)
if(display_plot):
plt.figure(figsize=(7,7))
# traceplot(trace_linear[100:])
plt.tight_layout()
print(pm.summary(trace_linear))
return linear_model,trace_linear
def credible_interval_calculation(x_data_shared,trace_linear,linear_model):
n_samples=1000
ppc_CI = pm.sample_posterior_predictive(trace_linear,
model=linear_model,
progressbar=False,keep_size=False)
predicted = ppc_CI.posterior_predictive['y']
print(predicted.shape)
nb_point = x_data_shared.get_value().shape[0]
print(nb_point)
predicted = np.reshape(predicted, (n_samples, nb_point))
predicted_interval = []
for col in predicted.T:
predicted_loc = [np.quantile(col, x) for x in [0.0005, 0.005, 0.05]] + \
[np.mean(col)] + \
[np.quantile(col, x) for x in [0.95, 0.995, 0.9995]]
predicted_interval += predicted_loc
predicted_interval = np.array(predicted_interval)
predicted_interval = np.reshape(predicted_interval, (int(predicted_interval.size / 7), 7), order='C')
predicted_interval = pd.DataFrame(predicted_interval, columns=('0.05%', '0.5%', '5.%',
'mean',
'95.%', '99.5%', '99.95%'))
print('predicted_interval:', predicted_interval)
predicted_interval['x'] = x_data_shared.get_value()#x_for_interp
return (predicted_interval, predicted)
Error:
Output exceeds the size limit. Open the full output data in a text editor
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In [148], line 42
37 bayes_reg.limit_y = LSL_table.loc[idx, ].iloc[0, 0]
39 bayes_reg.fit(df_reg[test_for_reg[0]],
40 df_reg[test_for_reg[1]],
41 Intercept = True)
---> 42 bayes_reg.credible_interval()
43 bayes_reg.credible_interval_loc([bayes_reg.limit_x])
44 #bayes_reg.distribution_plot_at_x()
Cell In [124], line 25, in release_test_correlation.credible_interval(self, nb_points)
23 self.x_data_shared.set_value(x_for_interp)
24 self.y_data_shared.set_value(np.zeros_like(x_for_interp))
---> 25 self.credible_interval_result, self.sampled_posterior_CI = credible_interval_calculation(self.x_data_shared,
26 self.trace_linear, self.linear_model)
Cell In [147], line 3, in credible_interval_calculation(x_data_shared, trace_linear, linear_model)
1 def credible_interval_calculation(x_data_shared,trace_linear,linear_model):
2 n_samples=1000
----> 3 ppc_CI = pm.sample_posterior_predictive(trace_linear,
4 model=linear_model,
5 progressbar=False,keep_size=False)
6 predicted = ppc_CI.posterior_predictive['y']
7 print(predicted.shape)
File c:\ProgramData\MiniforgeEnvs\pymc_env\lib\site-packages\pymc\sampling.py:1983, in sample_posterior_predictive(trace, samples, model, var_names, keep_size, random_seed, progressbar, return_inferencedata, extend_inferencedata, predictions, idata_kwargs, compile_kwargs)
1981 converter.nchains = nchain
1982 converter.ndraws = len_trace
-> 1983 idata_pp = converter.to_inference_data()
1984 if extend_inferencedata:
1985 trace.extend(idata_pp)
File c:\ProgramData\MiniforgeEnvs\pymc_env\lib\site-packages\pymc\backends\arviz.py:520, in InferenceDataConverter.to_inference_data(self)
509 def to_inference_data(self):
510 """Convert all available data to an InferenceData object.
511
512 Note that if groups can not be created (e.g., there is no `trace`, so
513 the `posterior` and `sample_stats` can not be extracted), then the InferenceData
514 will not have those groups.
515 """
516 id_dict = {
517 "posterior": self.posterior_to_xarray(),
518 "sample_stats": self.sample_stats_to_xarray(),
519 "log_likelihood": self.log_likelihood_to_xarray(),
--> 520 "posterior_predictive": self.posterior_predictive_to_xarray(),
521 "predictions": self.predictions_to_xarray(),
522 **self.priors_to_xarray(),
523 "observed_data": self.observed_data_to_xarray(),
524 }
525 if self.predictions:
526 id_dict["predictions_constant_data"] = self.constant_data_to_xarray()
File c:\ProgramData\MiniforgeEnvs\pymc_env\lib\site-packages\arviz\data\base.py:65, in requires.__call__.<locals>.wrapped(cls)
63 if all((getattr(cls, prop_i) is None for prop_i in prop)):
64 return None
---> 65 return func(cls)
File c:\ProgramData\MiniforgeEnvs\pymc_env\lib\site-packages\pymc\backends\arviz.py:444, in InferenceDataConverter.posterior_predictive_to_xarray(self)
441 @requires(["posterior_predictive"])
442 def posterior_predictive_to_xarray(self):
443 """Convert posterior_predictive samples to xarray."""
--> 444 return self.translate_posterior_predictive_dict_to_xarray(
445 self.posterior_predictive, "posterior_predictive"
446 )
File c:\ProgramData\MiniforgeEnvs\pymc_env\lib\site-packages\pymc\backends\arviz.py:439, in InferenceDataConverter.translate_posterior_predictive_dict_to_xarray(self, dct, kind)
432 if warning_vars:
433 warnings.warn(
434 f"The shape of variables {', '.join(warning_vars)} in {kind} group is not compatible "
435 "with number of chains and draws. The automatic dimension naming might not have worked. "
436 "This can also mean that some draws or even whole chains are not represented.",
437 UserWarning,
438 )
--> 439 return dict_to_dataset(data, library=pymc, coords=self.coords, dims=self.dims)
File c:\ProgramData\MiniforgeEnvs\pymc_env\lib\site-packages\arviz\data\base.py:307, in dict_to_dataset(data, attrs, library, coords, dims, default_dims, index_origin, skip_event_dims)
305 data_vars = {}
306 for key, values in data.items():
--> 307 data_vars[key] = numpy_to_data_array(
308 values,
309 var_name=key,
310 coords=coords,
311 dims=dims.get(key),
312 default_dims=default_dims,
313 index_origin=index_origin,
314 skip_event_dims=skip_event_dims,
315 )
316 return xr.Dataset(data_vars=data_vars, attrs=make_attrs(attrs=attrs, library=library))
File c:\ProgramData\MiniforgeEnvs\pymc_env\lib\site-packages\arviz\data\base.py:254, in numpy_to_data_array(ary, var_name, coords, dims, default_dims, index_origin, skip_event_dims)
252 # filter coords based on the dims
253 coords = {key: xr.IndexVariable((key,), data=np.asarray(coords[key])) for key in dims}
--> 254 return xr.DataArray(ary, coords=coords, dims=dims)
...
169 f"it has shape {v.shape!r} rather than expected shape {sizes[k]!r} "
170 "matching the dimension size"
171 )
ValueError: conflicting sizes for dimension 'chain': length 1 on the data but length 2 on coordinate 'chain'
<Figure size 700x700 with 0 Axes>