[英]Python curve_fit with multiple independent variables (in order to get the value for some unknow parameters)
Is there a way to use curve_fit to fit for a function with multiple independent variables like below?有没有办法使用 curve_fit 来拟合具有多个自变量的函数,如下所示?
I try to get the value for a1, b1, c1, a2, b2, c2, a3, b3, c3 and d while x1, x2, x3 and y1 (dependent variable) are all known.我尝试获取 a1、b1、c1、a2、b2、c2、a3、b3、c3 和 d 的值,而 x1、x2、x3 和 y1(因变量)都是已知的。 I want to optimize these values to minimize my error by using scipy.optimize.
我想通过使用 scipy.optimize 优化这些值以最小化我的错误。 Be noted in real situation, for x1, x2, x3 and y1, I have more than hundred data points.
请注意,在实际情况下,对于 x1、x2、x3 和 y1,我有一百多个数据点。
Or if there is a better way or more appropriate way to get the value for a1, b1, c1, a2, b2, c2, a3, b3, c3 and d?或者是否有更好的方法或更合适的方法来获取 a1、b1、c1、a2、b2、c2、a3、b3、c3 和 d 的值?
import numpy as np
from scipy.optimize import curve_fit
x1 = [3,2,1]
x2 = [3,4,2]
x3 = [1,2,4]
y1 = [5,7,9]
def func(x1, x2, a1, b1, c1, a2, b2, c2, d):
return (a1*x1**3+b1*x1**2+c1*x1) +(a2*x2**3+b2*x2**2+c2*x2) + d
def func2(x1, x2, x3, a1, b1, c1, a2, b2, c2, a3, b3, c3, d):
return (a1*x1**3+b1*x1**2+c1*x1) +(a2*x2**3+b2*x2**2+c2*x2) + (a3*x3**3+b3*x3**2+c3*x3) + d
You need to pass x1
and x2
in one object, see description of xdata
in docs for curve_fit
:您需要在一个对象中传递
x1
和x2
,请参阅curve_fit
文档中xdata
的描述:
The independent variable where the data is measured.
测量数据的自变量。 Should usually be an M-length sequence or an (k,M)-shaped array for functions with k predictors, but can actually be any object.
对于具有 k 个预测变量的函数,通常应该是 M 长度序列或(k,M) 形数组,但实际上可以是任何对象。
Example:例子:
import numpy as np
from scipy.optimize import curve_fit
# generate sample data for a1, b1, c1, a2, b2, c2, d = 1, 2, 3, 4, 5, 6, 7
np.random.seed(0)
x1 = np.random.randint(0, 100, 100)
x2 = np.random.randint(0, 100, 100)
y1 = (1 * x1**3 + 2 * x1**2 + 3 * x1) + (4 * x2**3 + 5 * x2**2 + 6 * (x2+np.random.randint(-1, 1, 100))) + 7
def func(x, a1, b1, c1, a2, b2, c2, d):
return (a1 * x[0]**3 + b1 * x[0]**2 + c1 * x[0]) + (a2 * x[1]**3 + b2 * x[1]**2 + c2 * x[1]) + d
popt, _ = curve_fit(func, np.stack([x1, x2]), y1)
Result:结果:
array([1.00000978, 1.99945039, 2.97065876, 4.00001038, 4.99920966,
5.97424668, 6.71464229])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.