以下代码来自http://cars9.uchicago.edu/software/python/lmfit/parameters.html上的示例。
from lmfit import minimize, Minimizer, Parameters, Parameter, report_fit
import numpy as np
# create data to be fitted
x = np.linspace(0, 15, 301)
data = (5. * np.sin(2 * x - 0.1) * np.exp(-x*x*0.025) +
np.random.normal(size=len(x), scale=0.2) )
# define objective function: returns the array to be minimized
def fcn2min(params, x, data):
""" model decaying sine wave, subtract data"""
amp = params['amp']
shift = params['shift']
omega = params['omega']
decay = params['decay']
model = amp * np.sin(x * omega + shift) * np.exp(-x*x*decay)
return model - data
# create a set of Parameters
params = Parameters()
params.add('amp', value= 10, min=0)
params.add('decay', value= 0.1)
params.add('shift', value= 0.0, min=-np.pi/2., max=np.pi/2)
params.add('omega', value= 3.0)
# do fit, here with leastsq model
minner = Minimizer(fcn2min, params, fcn_args=(x, data))
result = minner.minimize()
# calculate final result
final = data + result.residual
# write error report
report_fit(result)
# try to plot results
try:
import pylab
pylab.plot(x, data, 'k+')
pylab.plot(x, final, 'r')
pylab.show()
except:
pass
我试图在 Canopy 中运行此代码。当为 Python 3.5 使用 Canopy 64 位时,它运行良好。我需要使用 Python 2.7 在 Canopy 32 中使用它。当我更改为使用其他编辑器时,它不再起作用。这是它给我的问题:
13 omega = params['omega']
14 decay = params['decay']
---> 15 model = amp * np.sin(x * omega + shift) * np.exp(-x*x*decay)
16 return model - data
17 # create a set of Parameters
AttributeError: 'numpy.float64' object has no attribute 'sin'
我很困惑,因为我唯一改变的是 Python 的版本和 Canopy 的版本。这可能是由 Python 2.7 和 Python 3.5 之间的差异引起的吗?