将scipy curve_fit用于可变数量的参数 [英] Using scipy curve_fit for a variable number of parameters

查看:116
本文介绍了将scipy curve_fit用于可变数量的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个拟合函数,其形式为:

I have a fitting function which has the form:

def fit_func(x_data, a, b, c, N)

其中a,b,c是长度为N的列表,其每个条目都是在scipy.optimize.curve_fit()中进行优化,并且N是用于循环索引控制的固定数字。

where a, b, c are lists of lenth N, every entry of which is a variable parameter to be optimized in scipy.optimize.curve_fit(), and N is a fixed number used for loop index control.

跟随这个问题我认为我可以解决N,但是我现在按如下方式调用curve_fit:

Following this question I think I am able to fix N, but I currently am calling curve_fit as follows:

params_0 = [a_init, b_init, c_init]
popt, pcov = curve_fit(lambda x, a, b, c: fit_func(x, a, b, c, N), x_data, y_data, p0=params_0)

我得到一个错误:lambda()恰好接受了Q个参数(给定P)

I get an error: lambda() takes exactly Q arguments (P given)

其中Q和P取决于我如何进行设置。

where Q and P vary depending on how I am settings things up.

那么:对于初学者来说,这甚至可能吗?我可以将列表作为Curve_fit的参数传递,并具有我希望将列表元素视为单个参数的行为吗?并假设答案是肯定的,那么我的函数调用在做什么呢?

So: is this even possible, for starters? Can I pass lists as arguments to curve_fit and have the behavior I am hoping for wherein it treats list elements as individual parameters? And assuming that the answer is yes, what I am doing wrong with my function call?

推荐答案

这里的解决方案是编写一个包装函数,用于获取参数列表并将其转换为fit函数可以理解的变量。这实际上仅是必要的,因为我正在与其他人的代码一起工作,在更直接的应用程序中,无需包装层就可以工作。基本上

The solution here is to write a wrapper function that takes your argument list and translates it to variables that the fit function understands. This is really only necessary since I am working qwith someone else's code, in a more direct application this would work without the wrapper layer. Basically

def wrapper_fit_func(x, N, *args):
    a, b, c = list(args[0][:N]), list(args[0][N:2*N]), list(args[0][2*N:3*N])
    return fit_func(x, a, b, c, N)

要修复N,您必须像下面这样在curve_fit中调用它:

and to fix N you have to call it in curve_fit like this:

popt, pcov = curve_fit(lambda x, *params_0: wrapper_fit_func(x, N, params_0), x, y, p0=params_0)

其中

params_0 = [a_1, ..., a_N, b_1, ..., b_N, c_1, ..., c_N]

这篇关于将scipy curve_fit用于可变数量的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆