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

查看:33
本文介绍了在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 的参数之一.新创建的函数只接受两个参数:xa,而 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天全站免登陆