【问题标题】:SciPy curve_fit not working when one of the parameters to fit is a power当要拟合的参数之一是幂时,SciPy curve_fit 不起作用
【发布时间】:2016-12-27 01:46:20
【问题描述】:

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

【问题讨论】:

  • 我猜func2 在指数为小数时会因x-a 的负值而跳闸。有没有办法改变你的模型(也许抵消你的数据),让x-a更有可能是积极的?

标签: python-2.7 scipy curve-fitting


【解决方案1】:

(正如@xnx 首先评论的那样)第二个公式的问题(指数b 未知并被认为是实值)是,在测试a 和@ 的潜在值的过程中987654323@,需要计算z**p 形式的数量,其中z 是负实数,p 是非整数。这个数量通常是复杂的,因此该过程失败。例如,对于x=0 和测试变量a=0.5b=4.1,它拥有(x-a)**b = (-0.5)**4.1 = 0.0555+0.018j

【讨论】:

    猜你喜欢
    • 2016-09-16
    • 2017-04-27
    • 2012-11-02
    • 2014-05-29
    • 1970-01-01
    • 2017-04-11
    • 2017-04-07
    • 2017-07-13
    • 2021-12-30
    相关资源
    最近更新 更多