【发布时间】:2016-01-22 10:19:33
【问题描述】:
我正在尝试在 python 中使用 Scipy curve_fit 来拟合银河模型的两个全局参数。我有一个自变量数组和一个因变量数组。数据集的前 1/4 需要根据两个全局参数和两个局部参数拟合到一个函数,下一个季度根据两个全局参数和两个局部变量拟合到另一个函数等。
我是否可以编写一个函数,通过整个数组调用具有正确索引和全局参数的适当函数。
到目前为止我所拥有的是:
def galaxy_func_inner(time,a,b,c,d):
telescope_inner = lt.station(rot_angle=c,pol_angle=d)
power = telescope_inner.calculate_gpowervslstarray(time)[0]
return a*np.array(power)+b
def galaxy_func_outer(time,a,b,c,d):
telescope_outer = lt.station(rot_angle=c,pol_angle=d)
power = telescope_outer.calculate_gpowervslstarray(time)[0]
return a*np.array(power)+b
def galaxy_func_global(time,R,P,a,b,c,d,e,f,g,h):
for t_index in range(len(time)):
if t_index in range(0,50):
return galaxy_func_outer(t_index,a,b,R,P)
elif t_index in range(50,100):
return galaxy_func_outer(t_index,c,d,R,P)
elif t_index in range(100,150):
return galaxy_func_inner(t_index,e,f,R,P)
elif t_index in range(150,200):
return galaxy_func_inner(t_index,g,h,R,P)
问题是这个只适合第一次但是整个时间数组,并且单点只适合对应的模型点而不是整个数组。关于如何重新制定这个的任何帮助?我试图将其重新表述为:
def galaxy_func_global(xdata,R,P,a,b,c,d,e,f,g,h):
return galaxy_func_outer(xdata[0:50],a,b,R,P),galaxy_func_outer(xdata[50:100],c,d,R,P),galaxy_func_inner(xdata[100:150],e,f,R,P),galaxy_func_inner(xdata[150:200],g,h,R,P)
但我得到了错误:
File "galaxy_calibration.py", line 117, in <module>
popt,pcov = curve_fit(galaxy_func_global,xdata,ydata)
File "/Library/Python/2.7/site-packages/scipy-0.14.0.dev_7cefb25-py2.7-macosx-10.9-intel.egg/scipy/optimize/minpack.py", line 555, in curve_fit
res = leastsq(func, p0, args=args, full_output=1, **kw)
File "/Library/Python/2.7/site-packages/scipy-0.14.0.dev_7cefb25-py2.7-macosx-10.9-intel.egg/scipy/optimize/minpack.py", line 369, in leastsq
shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)
File "/Library/Python/2.7/site-packages/scipy-0.14.0.dev_7cefb25-py2.7-macosx-10.9-intel.egg/scipy/optimize/minpack.py", line 20, in _check_func
res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
File "/Library/Python/2.7/site-packages/scipy-0.14.0.dev_7cefb25-py2.7-macosx-10.9-intel.egg/scipy/optimize/minpack.py", line 445, in _general_function
return function(xdata, *params) - ydata
ValueError: operands could not be broadcast together with shapes (4,) (191,)
任何帮助将不胜感激。
【问题讨论】:
-
欢迎来到 Stack Overflow!如果您提供minimal reproducible example,您可能会得到更快的答复。我不清楚,例如:
galaxy_func_inner/outer是否期望时间或整数索引作为第一个参数?变量的命名建议使用前者,但是当您在global函数中调用这些函数时,您会给它们t_index而不是 t。
标签: python scipy curve-fitting