leastsq() 在 scipy.optimize.curve_fit 中得到参数 'x0' 错误的多个值

leastsq() got multiple values for argument 'x0' error in the scipy.optimize.curve_fit

我正在尝试输入一些初始猜测估计值 scipy.optimize.curve_fit 函数。 根据 this link another link

我应该在 x0 中定义它们,但是我尝试了不同的方法,但出现了以下错误。 (注意:没有x0参数,它工作正常)

TypeError: leastsq() 得到参数 'x0' 的多个值。

我在下面提供了一个可重现的例子:

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
import scipy.optimize
iris = load_iris()
data1 = pd.DataFrame(data= np.c_[ iris['target'], iris['data']],  columns=  ['target'] + iris['feature_names'] )

def formula_nls(data, pot, sp):
    return pot * np.tanh(data1.iloc[:,2] * sp / 2)

scipy.optimize.curve_fit(f = formula_nls, xdata= data1.iloc[:,1:],
                                                ydata= data1.iloc[:,0], method = 'lm',
                                             sigma = 1/data1.iloc[:,1], absolute_sigma=False,
                                                x0  = np.ndarray([ 1, 2]))

也许是我遗漏了一些简单的东西。 谢谢

curve_fit 的文档说:

时为什么要使用参数 x0

p0 : None, scalar, or N-length sequence, optional

Initial guess for the parameters. If None, then the initial values will all be 1 (if the number of parameters for the function can be determined using introspection, otherwise a ValueError is raised).

这与最小化和 least_squares 中的 API 不同,例如对于后者:

x0 : array_like with shape (n,) or float

Initial guess on independent variables. If float, it will be treated as a 1-d array with one element.

是的,在 curve_fit 内部,您给定 p0 becomes least_squares 中的 x0:

res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)

因为 x0 不是 curve_fit 的参数,我希望它被视为用于:

的参数

kwargs

Keyword arguments passed to leastsq for method='lm' or least_squares otherwise.

这意味着它将作为 x0 传递给 leastsq,连同来自 curve_fit!

的调用的 x0

像这样:

def fun(x0, **kwargs):
    return 1

print(fun(1))
# 1
print(fun(1, x0=3))
# TypeError: fun() got multiple values for argument 'x0'