Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Least-square fitting, confusing assignment query for python scipy

I'm new to this and have been looking at this for hours, comparing it with other least-square fitting examples, but the example code does not seem to click.

From http://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html the code is

>>> 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()

In the residuals function, why is it that 3 objects, A,k,theta can be assigned to p? Any help is appreciated

like image 741
psq Avatar asked May 13 '26 16:05

psq


1 Answers

The residuals function makes use of tuple unpacking to retrieve the elements of the sequence p. A simpler example of tuple unpacking may be:

x = ['One', 'Two', 'Three']

a,b,c = x

print(a) # One

In the case of the residuals function it makes it easier to read (using A, k, theta rather than p[0], p[1], p[2] respectively).

like image 60
Ffisegydd Avatar answered May 15 '26 05:05

Ffisegydd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!