将参数传递给函数以进行拟合 [英] passing arguments to a function for fitting

查看:126
本文介绍了将参数传递给函数以进行拟合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图拟合一个函数,该函数将2个独立变量x,y和3个参数作为a,b,c输入。这是我的测试代码:

I am trying to fit a function which takes as input 2 independent variables x,y and 3 parameters to be found a,b,c. This is my test code:

import numpy as np
from scipy.optimize import curve_fit

def func(x,y, a, b, c):
    return a*np.exp(-b*(x+y)) + c    

y= x = np.linspace(0,4,50)
z = func(x,y, 2.5, 1.3, 0.5) #works ok
#generate data to be fitted
zn = z + 0.2*np.random.normal(size=len(x))
popt, pcov = curve_fit(func, x,y, zn) #<--------Problem here!!!!!

但是我遇到了错误: func()恰好接受5个参数(给定51个)。如何正确传递参数x,y?

But i am getting the error: "func() takes exactly 5 arguments (51 given)". How can pass my arguments x,y correctly?

推荐答案

看看 scipy.optimize.curve_fit() 的文档a>就是全部。原型是

A look at the documentation of scipy.optimize.curve_fit() is all it takes. The prototype is

scipy.optimize.curve_fit(f, xdata, ydata, p0=None, sigma=None, **kw)

文档说明 curve_fit()以目标函数为第一个调用自变量作为第二个自变量,因变量作为第三个自变量,并将参数的起始值作为第四自变量。您尝试以完全不同的方式调用该函数,因此它不起作用并不奇怪。具体来说,您传递了 zn 作为 p0 参数–这就是为什么要使用这么多参数调用该函数的原因。

The documentation states curve_fit() is called with the target function as the first argument, the independent variable(s) as the second argument, the dependent variable as the third argument ans the start values for the parameters as the forth argument. You tried to call the function in a completely different way, so it's not surprising it does not work. Specifically, you passed zn as the p0 parameter – this is why the function was called with so many parameters.

文档还描述了如何调用目标函数:

The documentation also describes how the target function is called:


f :可调用

模型函数 f(x,...)。它必须将自变量作为第一个参数,并将参数作为单独的其余参数容纳。

f: callable
The model function, f(x, ...). It must take the independent variable as the first argument and the parameters to fit as separate remaining arguments.

xdata :An N 个长度的序列或(k,N)形数组

用于具有k个预测变量的函数。测量数据的自变量。

xdata : An N-length sequence or an (k,N)-shaped array
for functions with k predictors. The independent variable where the data is measured.

您尝试使用分隔变量的自变量,尽管它应该是一个参数数组。固定的代码如下:

You try to uses to separate arguments for the dependent variables, while it should be a single array of arguments. Here's the code fixed:

def func(x, a, b, c):
    return a * np.exp(-b * (x[0] + x[1])) + c    

N = 50
x = np.linspace(0,4,50)
x = numpy.array([x, x])          # Combine your `x` and `y` to a single
                                 # (2, N)-array
z = func(x, 2.5, 1.3, 0.5)
zn = z + 0.2 * np.random.normal(size=x.shape[1])
popt, pcov = curve_fit(func, x, zn)

这篇关于将参数传递给函数以进行拟合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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