Skip to main content
 首页 » 编程设计

python之余弦波的贝叶斯拟合花费的时间比预期的要长

2024年12月31日8kenshinobiy

在最近的作业中,我被要求使用 Metropolis 算法对一组数据 a 和 b 执行贝叶斯拟合。给出a和b之间的关系:

e(t) = e_0*cos(w*t)

w = 2 * pi

Metropolis 算法是(它与其他拟合一起工作正常):

def metropolis(logP, args, v0, Nsteps, stepSize): 
 
    vCur = v0 
    logPcur = logP(vCur, *args) 
    v = [] 
    Nattempts = 0 
 
    for i in range(Nsteps): 
        while(True): 
            #Propose step: 
            vNext = vCur + stepSize*np.random.randn(*vCur.shape) 
            logPnext = logP(vNext, *args) 
            Nattempts += 1 
 
            #Accept/reject step: 
            Pratio = (1. if logPnext>logPcur else np.exp(logPnext-logPcur)) 
 
            if np.random.rand() < Pratio:  
                vCur = vNext 
                logPcur = logPnext 
                v.append(vCur) 
                break 
 
    acceptRatio = Nsteps*(1./Nattempts) 
    return np.array(v), acceptRatio 

我已经尝试贝叶斯拟合余弦波并使用上面的 Metropolis 算法:

e_0 = -0.00155  
 
def strain_t(e_0,t): 
    return e_0*np.cos(2*np.pi*t) 
 
data = pd.read_csv('stressStrain.csv') 
t = np.array(data['t']) 
e = strain_t(e_0,t) 
 
def logfitstrain_t(params,t,e): 
    e_0 = params[0] 
    sigmaR = params[1] 
    strainModel = strain_t(e_0,t) 
    return np.sum(-0.5*((e-strainModel)/sigmaR)**2 - np.log(sigmaR)) 
 
 
params0 = np.array([-0.00155,np.std(t)])  
params, accRatio = metropolis(logfitstrain_t, (t,e), params0, 1000, 0.042) 
print('Acceptance ratio:', accRatio) 
 
e0 = np.mean(params[0]) 
print('e0=',e0) 
 
e_t = e0*np.cos(2*np.pi*t) 
sns.jointplot(t, e_t, kind='hex',color='purple') 

.csv 中的数据看起来像

我点击运行后没有显示任何错误消息,但 python 需要很长时间才能给我输出。 我在这里做错了什么?

请您参考如下方法:

为什么它可能“永远”

您的算法旨在运行,直到它接受 给定数量的提案(示例中为 1000)。因此,如果它运行了很长时间,您可能会拒绝一堆建议。当步长太大时会发生这种情况,导致新提议最终出现在似然空间的遥远、低概率区域。 尝试减小您的步长。这可能还需要您增加样本数量以确保充分探索后部空间。

更严重的问题

因为你只是将accepted proposals附加到链v,你并没有真正实现Metropolis算法,而是获得了一组倾向于过度代表不太可能的后空间区域。每当新提案被拒绝时,真正的 Metropolis 实现会重新附加先前的提案。您仍然可以执行最低数量的已接受提案,但您确实必须每次都附加一些内容。