中的Python double_标量溢出scipy.optimiz公司

2024-09-26 22:43:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图优化一系列函数的参数,使之与一组数据最佳匹配。在

当我执行脚本时,对于某些循环,函数正常工作,对于某些循环,我得到以下消息:

script.py:37: RuntimeWarning: overflow encountered in 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: invalid value encountered in double_scalars grad[k] = (f(
((xk + d,) + args)) - f0) / d[k]

我无法解决它,因为它似乎不是来自我,因为这个函数适用于某些数据集,而不适用于其他数据集。我不认为这是数据格式的问题,因为它是.txt文件中的所有数字。更奇怪的是,有时函数对一组数字有效,但对同一组的子集无效。在

有什么想法吗?在

代码如下。我在Windows8上使用Python2.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)

Tags: the函数infromtxtlogforreturn

热门问题