Aaron ChenAaron ChenAaron Chen SciPy-1 SciPy 1

Least-square fitting

For database (x[i], y[i]), we know there is functional relation called y=f(x), we know the f(x) as the f(x) = f(x, p), p is the set of undetermined coefficient. We need to know the p to make S the least :
$$
S(p) = sum_{i=1}^{m}[y_i - f(x_i, p)]^2
$$
We use the bank optimize in scipy to realize the function of leastsq.

Here is the example. We are trying to fit a sine wave function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# -*- coding: utf-8 -*-
import numpy as np
from scipy.optimize import leastsq
import pylab as pl

def func(x, p):
A, k, theta = p
return A*np.sin(2*np.pi*k*x+theta)

def residuals(p, y, x):
return y - func(x, p)

x = np.linspace(0, -2*np.pi, 100)
A, k, theta = 10, 0.34, np.pi/6
y0 = func(x, [A, k, theta])
y1 = y0 + 2 * np.random.randn(len(x))

p0 = [7, 0.2, 0]

plsq = leastsq(residuals, p0, args=(y1, x))

pl.plot(x, y0, label = "Real Data")
pl.plot(x, y1, label = "Experimental Data")
pl.plot(x, func(x, plsq[0]), label = "Fitted Data")
pl.legend()
pl.show()

Here is the result.