簡體   English   中英

在Python中傳遞返回NaN的函數的輸入

[英]Passing input of a function returning NaN in Python

我正在使用EMCEE 我在下面寫了一個從那里引起問題的部分。 我遇到此錯誤ValueError: lnprob returned NaN.

此錯誤中斷了計算,我不知道該如何克服。 因此,我應該做一些事情來傳遞這個錯誤,以便繼續進行其余的計算。

我唯一想到的就是在lnprob函數中添加一行,例如:

 if not np.isfinite(lp):
        return -np.inf
 if  np.isnan(lp):
        return -np.inf

但這是不正確的

代碼是:

def log_prior(H0, od0, c, b, Orc, M):
    if  0.4 < od0 < 0.9 and  50 < H0 < 90  and  0 < c < 3 and  0 < b < 1  and  -0.3 < M < 0.2 and  0 < Orc < 0.1:
        return 0.0
    return -np.inf

def lnlike(H0, od0, c, b, Orc, M):
    lg = -chi2(H0, od0, c, b, Orc, M)/2.
    return lg

def lnprob(H0, od0, c, b, Orc, M):
    lp = log_prior(H0, od0, c, b, Orc, M)
    if not np.isfinite(lp):
        return -np.inf
    return lp + lnlike(H0, od0, c, b, Orc, M)

def func(theta):
    H0, od0, c, b, Orc, M = theta
    return -2. * lnprob(H0, od0, c, b, Orc, M)

我感謝您的幫助。

我只想說python如果lnprob是NaN,沒關系,繼續其他值

如果仍然適合您,請執行以下操作:

def func(theta):
    H0, od0, c, b, Orc, M = theta
    try:
       lnprobval = -2. * lnprob(H0, od0, c, b, Orc, M)
    except ValueError: # NaN value case
       lnprobval = -np.inf # just set to negative infinity 
    return lnprobval

該代碼應替換def func(theta)return語句

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM