首页 文章

当其中一个适合的参数是功率时,SciPy curve_fit无法工作

提问于
浏览
1

我正在尝试使用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]]

1 回答

  • 2

    (正如@xnx首先评论的那样)第二个公式(其中指数 b 未知且被认为是实值)的问题在于,在测试 ab 的潜在值的过程中,需要 z**p 形式的数量要评估,其中 z 是负实数, p 是非整数 . 这个数量一般很复杂,因此程序失败 . 例如,对于 x=0 和测试变量 a=0.5b=4.1 ,它保存 (x-a)**b = (-0.5)**4.1 = 0.0555+0.018j .

相关问题