在python中仅将函数的一个参数与多个参数拟合 [英] Fitting only one parameter of a function with many parameters in python

查看:225
本文介绍了在python中仅将函数的一个参数与多个参数拟合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,我有一个具有许多参数的函数。我想将此功能适合数据集,但只使用一个参数,其余的参数我要自己提供。下面是一个示例:

In python I have a function which has many parameters. I want to fit this function to a data set, but using only one parameter, the rest of the parameters I want to supply on on my own. Here is an example:

def func(x,a,b):
   return a*x*x + b

for b in xrange(10):
   popt,pcov = curve_fit(func,x1,x2)

在此,我只想对 a 和参数 b 接受循环变量的值。

In this I want that the fitting is done only for a and the parameter b takes the value of the loop variable. How can this be done?

推荐答案

您可以将 func 包装在lambda,如下所示:

You can wrap func in a lambda, as follows:

def func(x,a,b):
   return a*x*x + b

for b in xrange(10):
   popt,pcov = curve_fit(lambda x, a: func(x, a, b), x1, x2)

lambda是一个匿名函数,在Python中只能用于简单的单行函数。基本上,通常在不需要为函数分配名称时通常用于减少代码量。官方文档中提供了更详细的描述: http://docs.python.org/tutorial/controlflow .html#lambda-forms

A lambda is an anonymous function, which in Python can only be used for simple one line functions. Basically, it's normally used to reduce the amount of code when don't need to assign a name to the function. A more detailed description is given in the official documentation: http://docs.python.org/tutorial/controlflow.html#lambda-forms

在这种情况下,lambda用于修复 func 。新创建的函数仅接受两个参数: x a ,而 b 固定为从本地 b 变量获取的值。然后,将此新函数作为参数传递到 curve_fit 中。

In this case, a lambda is used to fix one of the arguments of func. The newly created function accepts only two arguments: x and a, whereas b is fixed to the value taken from the local b variable. This new function is then passed into curve_fit as an argument.

这篇关于在python中仅将函数的一个参数与多个参数拟合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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