所以我在这里遇到这段代码的麻烦:

import numpy as np
import matplotlib.pyplot as plt
import scipy as sy
import pylab as plb

def oscDecay(x, A, B, C, tau, omega):
    return A*(1+B*np.cos(omega*x))*np.exp(-1*x**2/(2*tau**2))+C


def LMfit(func, x, y, p0, sig):
    #Fits data to non-linear curve using Levenberg-Marquart Method
    #Inputs: func = the function you are fitting data to
    #        x, y = data set
    #       p0 = tuple containing inital guesses for fitting  parameters
    #       sig = uncertainty in values
    #Outputs: nlfit = array containing optimal values for fitting parameters
    #       nlcov = two dimensional array (square root of diagonals contain
    #               uncertainty in fitting parameters)
    nlfit, nlpcov = sy.optimize.curve_fit(func, x, y, p0, sig)
    return nlfit, nlpcov

data=np.loadtxt('testing.txt', skiprows=4)

x=data[:, 0]
y=data[:, 1]
sig=data[:, 2]

#intial parameters
A0=16.5
B0=0.57
C0=17
tau0=30
omega0=7
p0=(A0, B0, C0, tau0, omega0)

nlfit, nlpcov = LMfit(oscDecay, x, y, p0, sig)


当我尝试运行它时,出现以下错误消息:

nlfit,nlpcov = sy.optimize.curve_fit(oscDecay,x,y,p0,sig)。
AttributeError:“模块”对象没有属性“优化”

我不确定这是什么意思,因为我的软件已经为我提供了scipy.optimize。

最佳答案

在您的情况下,导入似乎未按照评论者的说明进行。
我必须制作一个合成样本来测试您的代码。我只是省略了西格玛,并且一切正常(使用Ipython笔记本)。

import numpy as np
import matplotlib.pyplot as p
from scipy import optimize as opt
%matplotlib inline

def oscDecay(x, A, B, C, tau, omega):
    return A*(1+B*np.cos(omega*x))*np.exp(-1*x**2/(2*tau**2))+C

# make an example of data with some experimental noise
def oscDecayexp(x, A, B, C, tau, omega):
    rand=np.random.rand(len(x))
    return A*(1+(B+rand/10)*np.cos(omega*x))*np.exp(-1*x**2/(2*tau**2))+C


def LMfit(func, x, y, p0 ,sig=None):
    #Fits data to non-linear curve using Levenberg-Marquart Method
    #Inputs: func = the function you are fitting data to
    #        x, y = data set
    #       p0 = tuple containing inital guesses for fitting  parameters
    #       sig = uncertainty in values
    #Outputs: nlfit = array containing optimal values for fitting parameters
    #       nlcov = two dimensional array (square root of diagonals contain
    #               uncertainty in fitting parameters)
    nlfit, nlpcov = opt.curve_fit(func, x, y, p0, sig)
    return nlfit, nlpcov


#intial parameters
A0=16.5
B0=0.57
C0=17
tau0=30
omega0=7

x=np.arange(0,80,0.02)
y=oscDecayexp(x,A0,B0,C0,tau0,omega0)

p.figure(figsize=(12,8))

p.plot(x, oscDecay(x,A0,B0,C0,tau0,omega0)) # blue
p.plot(x, oscDecayexp(x,A0,B0,C0,tau0,omega0),lw=0.5) #green

p0=(A0, B0, C0, tau0, omega0)
# scipy.optimize.curve_fit(f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False, check_finite=True, **kw)
nlfit, nlpcov = LMfit(oscDecay, x, y, p0 )

print nlfit


输出:

python - Python(scipy.optimize.curve_fit问题)-LMLPHP

关于python - Python(scipy.optimize.curve_fit问题),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37107627/

10-12 19:00