[英]Dynamically create SciPy curve_fit function
SO noob here.所以菜鸟在这里。
I am creating a wrapper around scipy.optimize.curve_fit for multivariate regression.我正在为多元回归创建一个围绕 scipy.optimize.curve_fit 的包装器。 I was able to successfully run a vanilla version with two or three independent variables -我能够成功运行带有两个或三个自变量的 vanilla 版本 -
Two independent variables -两个自变量——
def fn(x, a, b1, b2):
return a + b1*x[0] + b2*x[1]
popt, pcov = curve_fit(fn, x, y)
Three independent variables -三个自变量——
def fn(x, a, b1, b2, b3):
return a + b1*x[0] + b2*x[1] + b3*x[2]
popt, pcov = curve_fit(fn, x, y)
The thing is, I don't know how many independent variables will there be in input and I don't want to iterate through all permutations of the function definition manually, which I also don't think is the best practice.问题是,我不知道输入中有多少个自变量,我不想手动遍历函数定义的所有排列,我也不认为这是最佳实践。 So the question is How to create the function fn
dynamically here based on the input dataframe?所以问题是如何根据输入数据帧在这里动态创建函数fn
?
This is not a very elegant solution, but you can always generate Python code from strings using the exec
command like this .这不是一个非常优雅的解决方案,但您始终可以使用像这样的exec
命令从字符串生成 Python 代码。 Then you can just generate a string dynamically for your function definitions and with exec
actually create the function.然后您可以为您的函数定义动态生成一个字符串,并使用exec
实际创建该函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.