我对此并不熟悉,已经研究了几个小时,将其与其他最小二乘拟合示例进行了比较,但示例代码似乎不太对劲。
来自http://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html的代码是
>>> from numpy import *
>>> x = arange(0,6e-2,6e-2/30)
>>> A,k,theta = 10, 1.0/3e-2, pi/6
>>> y_true = A*sin(2*pi*k*x+theta)
>>> y_meas = y_true + 2*random.randn(len(x))
>>> def residuals(p, y, x):
... A,k,theta = p
... err = y-A*sin(2*pi*k*x+theta)
... return err
>>> def peval(x, p):
... return p[0]*sin(2*pi*p[1]*x+p[2])
>>> p0 = [8, 1/2.3e-2, pi/3]
>>> print(array(p0))
[ 8. 43.4783 1.0472]
>>> from scipy.optimize import leastsq
>>> plsq = leastsq(residuals, p0, args=(y_meas, x))
>>> print(plsq[0])
[ 10.9437 33.3605 0.5834]
>>> print(array([A, k, theta]))
[ 10. 33.3333 0.5236]
>>> import matplotlib.pyplot as plt
>>> plt.plot(x,peval(x,plsq[0]),x,y_meas,'o',x,y_true)
>>> plt.title('Least-squares fit to noisy data')
>>> plt.legend(['Fit', 'Noisy', 'True'])
>>> plt.show()在residuals函数中,为什么可以将3个对象A,k,θ分配给p?任何帮助我们都将不胜感激
发布于 2014-01-17 00:05:54
residuals函数利用tuple unpacking来检索序列p的元素。一个更简单的元组解包示例可能是:
x = ['One', 'Two', 'Three']
a,b,c = x
print(a) # One在residuals函数的情况下,它使其更容易阅读(分别使用A, k, theta而不是p[0], p[1], p[2] )。
https://stackoverflow.com/questions/21166647
复制相似问题