我正在尝试使用 SciPy curve_fit 将数据拟合到用户定义的函数,该函数在拟合具有固定幂 (func1) 的函数时有效。但是,当函数包含幂作为参数来拟合 (func2) 时, curve_fit 不起作用。
如果我使用关键字 p0 提供参数的初始猜测,Curve_fit 仍然不起作用。我无法使用 bounds 关键字,因为我拥有的 SciPy 版本没有它。
这个脚本说明了这一点:
import scipy
from scipy.optimize import curve_fit
import sys
print 'scipy version: ', scipy.__version__
print 'np.version: ', np.__version__
print sys.version_info
def func1(x,a):
return (x-a)**3.0
def func2(x,a,b):
return (x-a)**b
x_train = np.linspace(0, 12, 50)
y = func2(x_train, 0.5, 3.0)
y_train = y + np.random.normal(size=len(x_train))
print 'dtype of x_train: ', x_train.dtype
print 'dtype of y_train: ', y_train.dtype
popt1, pcov1 = curve_fit( func1, x_train, y_train, p0=[0.6] )
popt2, pcov2 = curve_fit( func2, x_train, y_train, p0=[0.6, 4.0] )
print 'Function 1: ', popt1, pcov1
print 'Function 2: ', popt2, pcov2
输出如下:
scipy version: 0.14.0
np.version: 1.8.2
sys.version_info(major=2, minor=7, micro=6, releaselevel='final', serial=0)
dtype of x_train: float64
dtype of y_train: float64
stack_overflow.py:14: RuntimeWarning: invalid value encountered in power
return (x-a)**b
Function 1: [ 0.50138759] [[ 3.90044196e-07]]
Function 2: [ nan nan] [[ inf inf]
[ inf inf]]
最佳答案
(正如 @xnx 首先评论的那样,)第二个公式的问题(其中指数 b
未知并被认为是实值)是,在测试潜在值的过程中a
和 b
,需要计算 z**p
形式的数量,其中 z
是负数实数,p
是非整数。一般来说,这个数量很复杂,因此该过程会失败。例如,对于 x=0
和测试变量 a=0.5
、b=4.1
,它包含 (x-a)**b = (-0.5)**4.1 = 0.0555+0.018j
。
关于python-2.7 - 当要拟合的参数之一是幂时,SciPy curve_fit 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39046818/