我正在尝试优化一系列函数的参数,以便最好地匹配一组数据。
当我执行脚本时,对于某些循环,该函数正常工作,对于某些循环,我得到以下消息:
script.py:37:runtimeWarning:在double_scalars中遇到溢出 h.append(X [2] + X [0] * E [I] ** 2 + X [1]的 H [I])
C:\ Users \ ... \ Anaconda2 \ lib \ site-packages \ scipy \ optimize \ optimize.py:628:RuntimeWarning:double_scalars中遇到无效值 grad [k] =(f(((xk + d,)+ args)) - f0)/ d [k]
我无法解决它,因为它似乎不是来自我,因为该函数适用于某些数据集而不适用于其他数据。我不认为这是数据格式的问题,因为它是.txt
文件上的所有数字。更奇怪的是,有时候函数适用于一组数字,但不适用于同一组的子集。
有什么想法吗?
代码如下。我在Windows 8上使用python 2.7.12。
from numpy import *
from scipy import stats
from scipy import optimize
from math import *
#Get the data
price=loadtxt("DAX.txt")
#define arrays for return and excess return
r=[]
subr=[]
e=[]
optimparams = []
listsuml=[]
#calculate return
for i in range(len(price)-1):
r.append(log(price[i+1]/price[i]))
def sumloglikelihood (x):
#define function parameters
h=[]
z=[]
l=[]
h.append(sigma**2)
for i in range(999):
h.append(x[2]+x[0]*e[i]**2+x[1]*h[i])
for i in range(1000):
z.append(e[i]/sqrt(h[i]))
l.append(-0.5*(log(2*math.pi)+log(h[i])+z[i]**2))
#sum of log likelihoods
suml=0
for i in range(1000):
suml=suml+l[i]
suml=-suml
return suml
#for j in range (len(r)-1000):
for j in range (1):
del subr[:]
del e[:]
for i in range(1000):
subr.append(r[j+i])
#calculate some stats about the return
mu=mean(subr)
sigma=std(subr)
#calculate the excessive return
for i in range(1000):
e.append(subr[i]-mu)
params=[.06,.92]
params.append(sigma**2*(1-params[0]-params[1]))
#define the function to be minimized
#optimise the function and print the sum of log likelihoods with the new parameters
xxx=optimize.minimize(sumloglikelihood,params,method='L-BFGS-B',bounds=((.000001,3),(.000001,3),(.000001,3)))
optimparams.append(xxx.x)
listsuml.append(sumloglikelihood(optimparams[j]))
print optimparams
print listsuml
savetxt("optimparamsDAX.txt",optimparams)
savetxt("listsumlDAX.txt",listsuml)