所以我在这里遇到了这段代码的问题:
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已经可以使用。
答案 0 :(得分:1)
在您的情况下,导入似乎没有按评论者的说明起作用。 我必须制作一个合成样本来测试你的代码。我只是遗漏了sigmas并且它工作正常(使用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
输出: