0

我有以下关于约束参数的代码。运行代码时出现此错误:

samples[:, 2] = np.exp(samples[:, 2]) IndexError: index 2 is out of bounds for axis 1 with size 2

任何帮助请,我应该如何解决这个错误?感谢您的帮助和关注 import numpy as np import emcee import matplotlib.pyplot as plt from math import * import numpy as np from scipy.integrate import quad from 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)
4

1 回答 1

1

您有 2 个参数O_m,并M为它们设置了一个范围。但你[:,2]来了。2代表3个参数!我们从 0 而不是 1 开始。这是 Numpy。那么你想为你的代码定义 3 个输出!m_mcmc, b_mcmc, f_mcmc 这必须是 2 个输出而不是 3 个。我不确定 m 和 b 和 f 是什么。但我知道他们必须删除一个。然后你得到了答案。

于 2018-03-01T20:26:28.050 回答