import numpy as np def fit(x,y,m,w): if len(x)<=m: return False xishu = (x,y,m,w=w) p = np.poly1d(xishu) # Construct polynomials yfit = p(x) # fitted y-values yresid = y - yfit # Residuals SSresid = sum(pow(yresid, 2)) # Residual sum of squares SStotal = len(y) * (y) # Overall average variance if SStotal==0:# Horizontal line r2=1 else: r2 = 1 - SSresid/SStotal # Goodness of fit return (xishu,r2,yfit) if __name__=="__main__": x = (0,5,0.1) z = [2+3*x+4*x**2 for x in x] y = ([(z,3) for z in z]) weight=[1 for one in x] print(fit(x,y,2,weight))
polyfit(x,y,m,w) The parameter m is the number of polynomials +1 and w is the weight. The meaning of weight is that the error of this data point should be multiplied by the weight, and giving high weight to the low point can reduce the error of the low point and avoid the relative error of the low point is too large.
The return values (xishu,r2,yfit) of the custom function fit(x,y,m,w) are the coefficients, correlation coefficients, and fitted Y-values, respectively.
Crossing the origin can also be achieved by weights.The code is as follows:
if must00: x=(x,0)#.append(0) y=(y,0)#(0) w=(w,100000000)#.append(10000) fit_r=fit(x,y,m,w) if fit_r: (xishu,r,y_fitted)=fit_r else: #fit error xishu=[0,1,0] y_fitted=x r=0
summarize
To this article on the use of numpy polynomial fitting function polyfit is introduced to this article, more related numpy polynomial fitting function polyfi content, please search for my previous articles or continue to browse the following related articles I hope you will support me more in the future!