脚本打破负值scipy.optimize

时间:2014-09-12 10:35:51

标签: python numpy pandas scipy

我已经整理了以下脚本来优化常量公式中的常量。但是,脚本似乎在我的脚本中返回第二列的负值的初始猜测。 将data = data[:,:]更改为data = data[:,4:]或将数字更改为正数会使脚本运行。

import pandas as pd
import numpy as np
import scipy.optimize

data=[[2002.0,-0.08972958149990809,1826.0],
[2003.0,-0.04897683565290298,1892.0],
[2004.0,-0.07677738137813091,1967.0],
[2005.0,-0.005302134299962579,1948.0],
[2006.0,0.018232573476155322,1965.0],
[2007.0,0.11935334414772003,2040.0],
[2008.0,0.12924112452811573,2038.0],
[2009.0,0.2953328281033769,2080.0],
[2010.0,0.3517136208952717,2104.0],
[2011.0,0.38644008336056207,2107.0]]

data = data[:,:]

def model(p,x):
    year,gdp = x[:,0],x[:,1]
    return function(p,gdp,year)

def function(p,gdp,year):
    a,b,c,d,i=p
    y=(a+year*b) * gdp ** (c + year * d) + i
    print 'y:',y
    return y

def residuals(p,y,x):
    return y - model(p,x)

p_guess=np.array([2.8,0,0.16,0,850])

p, cov, infodict, mesg, ier = scipy.optimize.leastsq(residuals,p_guess,args=(data[:,-1],data[:,0:2]),full_output=1) 

a,b,c,d,i=p
print('''\
a = {a}
b = {b}
c = {c}
d = {d}
i = {i}
'''.format(a=a,b=b,c=c,d=d,i=i))

1 个答案:

答案 0 :(得分:2)

您应该收到如下错误:

  

ValueError:负数不能提升到分数幂

因为您的负值被赋值给变量gdp,可以将其提升到分数幂。