Using Scipy curve_fit with variable number of parameters to optimize

血红的双手。 提交于 2019-12-02 03:54:08

It might be easier to construct the function as a string within a loop and use 'exec' to execute that string as a python code then use it in Scipy curve_fit:

N = 5

arg_k = ''
arg_a = ''

for i in range(N):
    arg_a += 'a'+str(i)+','
    arg_k += 'k'+str(i)+','

function_def = 'def radius (z,' +  arg_a+arg_k+ '):'
a = 'a = np.array(['+arg_a+'])' 
k = 'k = np.array(['+arg_k+'])'  
indent = '    '
function_def += ('\n'+indent+ k
                +'\n'+indent+ a 
                +'\n'+indent+'w   = 1.0'
                +'\n'+indent+'phi = 0.0'
                +'\n'+indent+'rs = r0 + np.sum(a*np.sin(k*z +w*t +phi), axis=1)'
                +'\n'+indent+'return rs')


exec(function_def)

printing the string gives the following result:

print(function_def)

def radius (z,a0,a1,a2,a3,a4,k0,k1,k2,k3,k4,):
    k = np.array([k0,k1,k2,k3,k4,])
    a = np.array([a0,a1,a2,a3,a4,])
    w   = 1.0
    phi = 0.0
    rs = r0 + np.sum(a*np.sin(k*z +w*t +phi), axis=1)
    return rs

Then use Scipy curve_fit on the defined function:

popt, pcov = curve_fit(radius, xdata=z, ydata=r)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!