python - Least square fit a 2D line -
i realize use numpy find line so:
import numpy np import matplotlib.pyplot plt = np.array([1,2,3,4,6,7]) b = np.array([5,4,3,2,-2,-1]) k,m = np.polyfit(a,b,1) plt.scatter(a,b) plt.plot([0,10],[m,10*k+m]) plt.show()
but i'd use raw python code instead. math rusty, if can done in few lines of code i'd appreciate help!
if looking simple linear regression based on minimizing quadratic error, pure python implementation pretty straightforward (check equations α , β on link above):
def linear_fit(x, y): """for set of points `(xi, yi)`, return linear polynomial `f(x) = k*x + m` minimizes sum of quadratic errors. """ meanx = sum(x) / len(x) meany = sum(y) / len(y) k = sum((xi-meanx)*(yi-meany) xi,yi in zip(x,y)) / sum((xi-meanx)**2 xi in x) m = meany - k*meanx return k, m
for sample input:
>>> x = [1,2,3,4,6,7] >>> y = [5,4,3,2,-2,-1] >>> linear_fit(x, y) (-1.1614906832298135, 6.285714285714285)
Comments
Post a Comment