-2
以下代碼來自http://cars9.uchicago.edu/software/python/lmfit/parameters.html上的示例。這是否是由Python 2.7和3.5中的差異引起的錯誤?
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的版本以及敞篷版本。這可能是由Python 2.7和Python 3.5的區別造成的嗎?
你可以在'decay = ...'行之後插入'print(type(np))'並報告輸出嗎? –
我對此表示懷疑。這個錯誤意味着'np'被綁定到'numpy.float64'對象。你有分配給'np ='嗎? –
@YakymPirozhenko'decay = ...'後'print(type(np))'的結果是'' –
kotval