gpt4 book ai didi

python - scipy 没有优化并返回 "Desired error not necessarily achieved due to precision loss"

转载 作者:太空狗 更新时间:2023-10-29 21:16:42 24 4
gpt4 key购买 nike

我有以下代码试图最小化对数似然函数。

#!/usr/bin/python
import math
import random
import numpy as np
from scipy.optimize import minimize

def loglikelihood(params, data):
(mu, alpha, beta) = params
tlist = np.array(data)
r = np.zeros(len(tlist))
for i in xrange(1,len(tlist)):
r[i] = math.exp(-beta*(tlist[i]-tlist[i-1]))*(1+r[i-1])
loglik = -tlist[-1]*mu
loglik = loglik+alpha/beta*sum(np.exp(-beta*(tlist[-1]-tlist))-1)
loglik = loglik+np.sum(np.log(mu+alpha*r))
return -loglik

atimes = [ 148.98894201, 149.70253172, 151.13717804, 160.35968355,
160.98322609, 161.21331798, 163.60755544, 163.68994973,
164.26131871, 228.79436067]
a= 0.01
alpha = 0.5
beta = 0.6
print loglikelihood((a, alpha, beta), atimes)

res = minimize(loglikelihood, (0.01, 0.1,0.1), method = 'BFGS',args = (atimes,))
print res

它给了我

28.3136498357
./test.py:17: RuntimeWarning: invalid value encountered in log
loglik = loglik+np.sum(np.log(mu+alpha*r))
status: 2
success: False
njev: 14
nfev: 72
hess_inv: array([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
fun: 32.131359359964378
x: array([ 0.01, 0.1 , 0.1 ])
message: 'Desired error not necessarily achieved due to precision loss.'
jac: array([ -2.8051672 , 13.06962156, -48.97879982])

请注意,它根本没有设法优化参数,最小值 32 大于 28,这是您使用 a= 0.01, alpha = 0.5, beta = 0.6 得到的值。通过选择更好的初始猜测可能可以避免此问题,但如果是这样,我如何自动执行此操作?

最佳答案

我复制了你的例子并尝试了一下。看起来如果您坚持使用 BFGS 求解器,在几次迭代后 mu+ alpha * r 将有一些负数,这就是您如何获得 RuntimeWarning。

我能想到的最简单的解决方法是切换到 Nelder Mead 求解器。

res = minimize(loglikelihood, (0.01, 0.1,0.1), method = 'Nelder-Mead',args = (atimes,))

它会给你这个结果:

28.3136498357
status: 0
nfev: 159
success: True
fun: 27.982451280648817
x: array([ 0.01410906, 0.68346023, 0.90837568])
message: 'Optimization terminated successfully.'
nit: 92

关于python - scipy 没有优化并返回 "Desired error not necessarily achieved due to precision loss",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24767191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com