Least squares fitting (scipy achieve)

Scipy library numpy library based on the increase of the number of mathematics, science and engineering calculation commonly used library functions. Such as linear algebra, numerical solution of ordinary differential equations, the signal processing, image processing, and the like sparse matrix.

Be understood that the following least squares fit calculation by Scipy

Least squares fitting (optimize Functions)

from scipy.optimize import leastsq 

optimize function containing functions leastsq Least Square Method,

By following the fitting of a sine function, obtained by least squares fitting parameters. func three parameters A, k, theta respectively correspond to amplitude, frequency, phase angle.

 

AS NP numpy Import 
from scipy.optimize Import leastsq 
Import pylab AS PL 
from pylab Import MPL 
mpl.rcParams [ 'serif-font.sans'] = [ 'Kaiti'] # Chinese distortion solution 
mpl.rcParams [ 'axes.unicode_minus'] = False # negative sign to solve the problem in block 

DEF FUNC (X, P): 

	# fitting the data used by the function: a * SiN (2 * PI * X + K * Theta) 

	a, K, P = Theta 
	return a np.sin * (2 * X + np.pi * K * Theta) 

DEF residuals (P, Y, X): 

	# experimental data x, y and a function of a difference between a fitting coefficient, p is the need to find the fitting 

	Y return - FUNC (X, P) 

X = np.linspace (0, -2 * np.pi, 100) # Create arithmetic sequence, the number 100 indicates the data points 
A, k, theta = 10, 0.34, np. function parameters pi / 6 # real data 
y0 = func (x, [a , k, theta]) # real data 
y1 = y0 + 2 * np.random.randn ( len (x)) # experimental noise data added 

p0 = [7,0.2,0] # guess first function fitting parameters

"" " 
	1, calls leastsq data fitting 
	2, residuals to calculate the error function 
	3, p0 is the initial value of the fitting parameter 
	4, args need to fit the experimental data for the 
" "" 
plsq = leastsq (residuals, P0, = args (Y1, X)) 

Print (U "true parameter:" [a, K, Theta]) 
Print (U "fitting parameters:", the parameter plsq [0]) # fitting the experimental data 

# as FIG 
pl.plot (x, y0, label = u ' real data') 
pl.plot (X, Y1, U label = 'experimental data noisy') 
pl.plot (X, FUNC (X, plsq [0] ), label = u "fit data") 
pl.legend () 
pl.show ()  

 Graphic shows:

 

Since the above can be seen that a periodic sinusoidal function, the law of movement and fitting parameters and real data are virtually identical.

 

Guess you like

Origin www.cnblogs.com/hqczsh/p/11297669.html