简体   繁体   English

如何在python中为多维数据实现非线性最小二乘法?

[英]How do I implement non-linear least squares for multidemnsional data in python?

I have to implement least square fitting algorithm for this model function 我必须为此模型函数实现最小二乘拟合算法

Y = a_0 * e^(a_1*x_1+a_2*x_2+...+a_n*x_n)

The approach I found was to define function to calculate residuals and pass it to scipy.optimize.leastsq or lmfit. 我发现的方法是定义函数以计算残差并将其传递给scipy.optimize.leastsq或lmfit。 Yet i cannot make it to work with multidimensional data, when parameters are vector and not single values. 但是,当参数是矢量而不是单个值时,我无法使它与多维数据一起使用。

def residual(variables,X,y):
    a_0 = variables[0]
    a = variables[1]

    return (y - a_0 * np.exp(X.dot(a)))**2

X = np.random.randn(100,5)
y = np.random.randint(low=0,high=2,size=100)
a_0 = 1
a = np.random.randn(X.shape[1])

leastsq(residual,[a_0,a],args=(X,y))

I get this error. 我得到这个错误。

ValueError: setting an array element with a sequence. ValueError:使用序列设置数组元素。

Can you point me the right course of action from here? 您能从这里为我指出正确的做法吗?

I think something like this should do the job : 我认为像这样的事情应该做的工作:

def residual(variables,X,y):
    a_0 = variables[0]
    a = variables[1:]

    return (y - a_0 * np.exp(X.dot(a)))**2

X = np.random.randn(100,5)
y = np.random.randint(low=0,high=2,size=100)
a = np.random.randn(X.shape[1]+1)
a[0] = 1

res = scipy.optimize.leastsq(residual,a,args=(X,y))

Regards 问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM