You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
defMetropolis_Hastings(parameter_init, nsteps):
result= [] # List to store the sampled parameter valuesresult.append(parameter_init) # Add the initial parameter values to the result listfortinrange(nsteps): # Iterate over the specified number of stepsstep_var= [1, 0.1] # Variance of the proposal distribution for each parameterproposal=norm.rvs(loc=result[-1], scale=step_var) # Generate a proposal parameter value from a normal distributionprobability=np.exp(posterior(proposal,z,hz,hzerr) -posterior(result[-1],z,hz,hzerr)) # Calculate the acceptance probabilityif (uniform.rvs() <probability): # Accept the proposal with the acceptance probabilityresult.append(proposal) # Add the proposal to the result listelse:
result.append(result[-1]) # Reject the proposal and add the previous parameter value to the result listreturn(result) # Return the sampled parameter values
fig, axes=plt.subplots(2, 1, figsize=(8, 8))
samples_b=samples_MH_b.T# Plot the traceplot of H0axes[0].plot(samples_b[0], "g")
axes[0].set_ylabel("$H_0$")
# Plot the traceplot of Omaxes[1].plot(samples_b[1], "r")
axes[1].set_ylabel("$\Omega_{m0}$")
13. Find Best Fit value of parameters
h0_chain=samples_MH_b[:,0]
om_chain=samples_MH_b[:,1]
#Estimate the mean of a and b chainsh0_best=np.mean(h0_chain)
om_best=np.mean(om_chain)
#Estimate the Std. Deviation of a and b chainssig_h0=np.std(h0_chain)
sig_om=np.std(om_chain)
print("Best fit values:")
print("H0:",h0_best, "Sig_h0:", sig_h0)
print("Om:",om_best, "Sig_om:", sig_om)
14. Show Parameter Histograms
plt.figure(figsize=(8, 3)) #Plot Size# Plot the histogram of aplt.subplot(1, 2, 1)
plt.hist(h0_chain, bins=100, color='blue')
plt.xlabel('H0')
plt.ylabel('Count')
# Plot the histogram of bplt.subplot(1, 2, 2)
plt.hist(om_chain, bins=100, color='blue')
plt.xlabel('Om')
plt.ylabel('Count')