Linear Fitting Using the least square method
# Coding: utf-8import numpy as npimport matplotlib. pyplot as pltdots = NP. array ([[], [], [], [], []) PLT. plot ([I [0] For I in DOTS], [I [1] For I in DOTS], 'ro') PLT. axis ([0, 6, 0, 12]) def nihezhixian (K, X, B ): return K * x + bsumxy = sum ([A [0] * A [1] For a in DOTS]) # print sumxysumxx = sum ([A [0] ** 2 for a in DOTS]) print sumxxsumx = sum ([A [0] For a in DOTS]) print sumxsumy = sum ([A [1] For a in DOTS]) # a0 = (Σ Yi)/n-A1 (Σ XI)/n (Formula 1-8) # a1 = [n Σ Xi Yi-(Σ Xi Σ Yi)]/[n Σ xi2-(Σ xi) 2)] (Formula 1-9) # print Dir (DOTS) n = dots. shape [0] K = float (N * sumxy-sumx * Sumy)/float (N * sumxx-sumx * sumx) # print A1 B = float (Sumy) /n-float (K * sumx)/NPLT. plot ([I [0] For I in DOTS], [nihezhixian (K, I [0], B) For I in DOTS]) PLT. show ()
The image output is as follows:
The problem solved by the least square method is: for a given series of points [(x1, Y1), (X2, Y2 )... (Xn, yn)], to Y's function about X.
Evaluate a Function Y = f (x) so that Y = f (x) can describe these column points, which solves the following equation:
Sum (f (xi)-yi) ** 2
There is a minimum value. In the linear fitting process, y = f (x) = ax + B. The above formula is used to calculate the minimum value. You only need to calculate the reciprocal of A and B.