我有以下代码来约束参数。 运行代码时出现此错误:
samples[:, 2] = np.exp(samples[:, 2])
IndexError: index 2 is out of bounds for axis 1 with size 2
任何帮助请,我该怎么做才能解决此错误?感谢您的帮助和关注 导入numpy为np 进口司仪 将matplotlib.pyplot导入为plt 从数学导入* 导入numpy为np 来自scipy.integrate import quad 来自scipy.integrate import odeint
xx=np.array([0.01,0.012,0.014,0.016]) #or xx=[0.01.......]
yy=np.array([32.95388698,33.87900347,33.84214074,34.11856704])
Cov=[[137,168],[28155,-2217]]
#Initial points
rc=0.09, c=0.7, H01 = 70, O_m1 = 0.31, z0=0, M=1, O_m = 0.31, H0=70
np.random.seed(123)
def ant(z,O_m,O_D): # first function
return 1/sqrt(((1+z)**2)*(1+O_m*z)-z*(2+z)*O_D)
def new_calculation(n):
O_D=1-O_m
q=quad(ant,0,xx[n],args=(O_m,O_D))[0] #using the first function in integration
h=log10((1+xx[n])*q)
fn=(yy[n]-M-h)
return fn
def log_likelihood(theta):
M, O_m= theta
f_list = []
for i in range(2): # the value '2' reflects matrix size
f_list.append(new_calculation(i))
rdag=[f_list]
rmat=[[f] for f in f_list]
mm=np.dot(rdag,Cov)
zz=np.dot(mm,rmat)
hh=np.linalg.det(zz)*0.000001
return hh #calculation of matrix
from scipy.optimize import minimize
np.random.seed(42)
nll = lambda *args: -log_likelihood(*args)
initial = np.array([M, O_m1]) + 0.1*np.random.randn(2)
soln = minimize(nll, initial)
M_ml, O_m0_ml = soln.x
def log_prior(theta):
M, O_m= theta
if 0.22 < O_m < 0.32 and 0 < M < 12:
return 0.0
return -np.inf
def log_probability(theta):
lp = log_prior(theta)
if not np.isfinite(lp):
return -np.inf
return lp + log_likelihood(theta)
pos = soln.x + 1e-4*np.random.randn(80, 2)
nwalkers, ndim = pos.shape
sampler = emcee.EnsembleSampler(nwalkers, ndim, log_probability)
sampler.run_mcmc(pos, 250);
samples = sampler.chain[:, 50:, :].reshape((-1, ndim))
from IPython.display import display, Math
samples[:, 2] = np.exp(samples[:, 2]) #the error may be resulted from here
m_mcmc, b_mcmc, f_mcmc = map(lambda v: (v[1], v[2]-v[1], v[1]-v[0]),
zip(*np.percentile(samples, [16, 50, 84],
axis=0)))
print(m_mcmc, b_mcmc)
答案 0 :(得分:1)
您有2个参数O_m
和M
,您可以为它们设置范围。但你在这里得到[:,2]
。 2是3个参数!我们从0开始而不是1.这是Numpy。
那么你想为你的代码定义3输出! m_mcmc, b_mcmc, f_mcmc
这必须是2个输出而不是3个。我不确定m和b和f是什么。但我知道一个人必须被删除。
然后你得到了答案。