1 ImportNumPy as NP2 3 defSumsquareerror (dataset,a):4 #Enter the target dataset with the assumed curve function, calculate the sum of squared errors5 #data form Dataset[i] = [X,y],y = Hypfunc (x)6 #A: Polynomial coefficients [a0,a1,..., an-1]7Hypresult = [Hypfunc (dataset[i,0],a) forIinchRange (dataset.shape[0])8SSE = Np.sum ((hypresult-dataset[:,1]) **2)9 returnSSETen One defHypfunc (x,a): A #Input: X horizontal value, A polynomial coefficient [a0,a1,..., an-1] - #return y = Hypfunc (x) - returnNp.sum (a[i]* (x**i) forIinchRange (len (A))) the - """ - The idea of least squares - Set Assumptions YH = a0x^0 + a1x^1 + a2x^2 +...+ akx^k + then the error R2 = SUM (Y (xi)-yh (xi)) i = 1...N - R2 = sum [(yi-(a0x^0 + a1x^1 + a2x^2 +...+ akx^k))]2 ~ 0 + R2 to AI: and make (a total of k+1 equations) A div (R2,ai) =-2 * SUM (yi-(a0x^0 + a1x^1 + a2x^2 +...+ akx^k)) * x^i = 0 at The following matrix is used to solve the equation - [[1 x1 ... x1^k],..., [1 xn ... xn^k]] * [a0,..., ak] = [y1,..., yn] - """ - - ImportRandom - ImportMatplotlib.pyplot as Plt in - if __name__=="__main__": to Pass + #generate points on a curve -x = Np.arange ( -1,1,0.02) they = [((a*a-1) * (a*a-1) * (a*a-1) +0.5) *np.sin (a*2) forAinchx] *Xa = [] $Ya = []Panax Notoginseng #randomly offsets each point on a curve - forIinchRange (len (x)): theD = np.float (Random.randint (60,140))/100 +Ya.append (y[i]*d) AXa.append (x[i]*d) then = Len (xa)#Number of data + -Order = 9#set the K-order polynomial 0 ~ k $ #constructing x, y Vandermonde matrices from data points $mATX = Np.array ([[[Np.sum] ([xa[i]** (K2+K1)] forIinchrange (n)]) - forK2inchRange (order+1)] forK1inchRange (order+1)]) - theMaty = Np.array ([Np.sum (Xa[i]**k) *ya[i] forIinchrange (n)]) - forKinchRange (order+1)])Wuyi PrintMatx.shape,maty.shape the -A =np.linalg.solve (mATX, Maty) Wu PrintA - About #draw data points and fit curves $ plt.figure () - #output data points -Plt.plot (xa,ya,linestyle="', marker='.') - A #draw a fitted post curve +Yhyp = [Hypfunc (x[i],a) forIinchrange (n)] thePlt.plot (x,yhyp,linestyle='-', marker="') - $Plt.show ()
least squares Python implementation