当要拟合的参数之一是幂时,SciPy curve_fit不起作用 [英] SciPy curve_fit not working when one of the parameters to fit is a power

查看:73
本文介绍了当要拟合的参数之一是幂时,SciPy curve_fit不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用SciPy curve_fit将数据拟合到用户定义的函数中,该函数在以固定功率(func1)拟合到函数时可以工作.但是,当函数包含幂作为参数来适合(func2)时,curve_fit不起作用.

I'm trying to fit my data to a user defined function using SciPy curve_fit, which works when fitting to a function with a fixed power (func1). But curve_fit does not work when the function contains a power as a parameter to fit to (func2).

Curve_fit仍然不起作用.我不能使用 bounds 关键字,因为我没有的SciPy版本.

Curve_fit still does not work if I provide an initial guess for the parameters usins the keyword p0. I can not use the bounds keyword as the version of SciPy which I have does not have it.

此脚本说明了这一点:

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 未知且被认为是实数)-valued)是,在测试 a b 的潜在值的过程中,需要将形式为 z ** p 的数量评估,其中 z 是负实数,而 p 是非整数.该数量通常很复杂,因此该过程失败.例如,对于 x = 0 和测试变量 a = 0.5 b = 4.1 ,它保存(xa)** b=(-0.5)** 4.1 = 0.0555 + 0.018j .

(As @xnx first commented,) the problem with the second formulation (where the exponent b is unknown and considered to be real-valued) is that, in the process of testing potential values for a and b, quantities of the form z**p need to be evaluated, where z is a negative real number and p is a non-integer. This quantity is complex in general, hence the procedure fails. For example, for x=0 and test variables a=0.5, b=4.1, it holds (x-a)**b = (-0.5)**4.1 = 0.0555+0.018j.

这篇关于当要拟合的参数之一是幂时,SciPy curve_fit不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆