1

我有一组数字,当我尝试对其进行曲线拟合时会导致错误。我很确定我以前用相同的数字做到了这一点(我确定我用其他数据集做过)。那么是什么导致了这个错误呢?

, X,YErr是(按出现顺序)

[0.0, 0.6931471805599453, 1.3862943611198906]
[-5.354761064902713, -6.190455611580044, -6.558604540577015]
[0.0014079400762288246, 0.0006083544693643583, 0.0002989970199491765]

并且kappa等于 8

这是我尝试拟合的函数(主要是 a + 2*x)

 out = []
    for x in X:
        y = log(kappa)
        y += 4*log(pi)
        y += 2*x 
        y -= 2*log(2)
        out.append(-y)
    return np.array(out)

这就是我所说的curve_fit

 popt,pcov = curve_fit(fitFunc1,self.X[0:3],self.Y[0:3],sigma=self.Err[0:3],p0=kappa)

这是我得到的错误

popt,pcov = curve_fit(fitFunc1,self.X[0:3],self.Y[0:3],sigma=self.Err[0:3],p0=kappa)
  File "/usr/lib/python2.7/dist-packages/scipy/optimize/minpack.py", line 506, in curve_fit
    res = leastsq(func, p0, args=args, full_output=1, **kw)
  File "/usr/lib/python2.7/dist-packages/scipy/optimize/minpack.py", line 355, in leastsq
    gtol, maxfev, epsfcn, factor, diag)
minpack.error: Error occurred while calling the Python function named _weighted_general_function

编辑 1

附加值kappa(8)


编辑 2

这是一个最小的工作示例

#!/usr/bin/python
import numpy as np
from scipy.optimize import curve_fit
from math import log,pi
X = [0.0, 0.6931471805599453, 1.3862943611198906]
Y = [-5.354761064902713, -6.190455611580044, -6.558604540577015]
Err = [0.0014079400762288246, 0.0006083544693643583, 0.0002989970199491765]
kappa = 8

def func(X,kappa):
    out = []
    for x in X:
        y = log(kappa)
        y += 4*log(pi)
        y += 2*x 
        y -= 2*log(2)
        out.append(-y)
    return np.array(out)


popt,pcov = curve_fit(func,X,Y,sigma=Err,p0=kappa)
4

1 回答 1

0

首先,将输入数组转换为 numpy 数组。这允许您在func. 此外,您应该检查是否kappa<=0并返回一个不合适的值,以防止在您可能感兴趣的域之外进行评估:

import numpy as np
from scipy.optimize import curve_fit
X = np.array([0.0, 0.6931471805599453, 1.3862943611198906])
Y = np.array([-5.354761064902713, -6.190455611580044, -6.558604540577015])
Err = np.array([0.0014079400762288246, 0.0006083544693643583, 0.0002989970199491765])
kappa = 8.0

def func(X,kappa):
    if kappa <=0: return np.inf
    return -(np.log(kappa) + 4*np.log(np.pi) + 2*X - 2*np.log(2))

popt,pcov = curve_fit(func,X,Y,sigma=Err,p0=kappa)
于 2013-09-30T14:45:38.640 回答