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

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

问题描述

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

I have a fitting function which has the form:

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

其中a、b、c是lenth 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?

推荐答案

这里的解决方案是编写一个包装函数,该函数接受您的参数列表并将其转换为适合函数理解的变量.这确实是必要的,因为我正在使用其他人的代码,在更直接的应用程序中,这将在没有包装层的情况下工作.基本上

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天全站免登陆