In [1]:
HW4 Problem:
Out[1]:
In [1]:
import numpy as np
import matplotlib.pyplot as plt
In [2]:
points = np.array([[2,2],[0,0],[-2,-2],[-1,1],[1,-1]])
In [3]:
x = points[:,0]
y = points[:,1]

1) Compute and draw best-fit line

In [4]:
fit = np.polyfit(x,y,1)
fit_fn = np.poly1d(fit)

plt.plot(x, y, 'yo', x, fit_fn(x), 'x--')
plt.xlim(-3, 3);plt.ylim(-3, 3);plt.grid();plt.show()
print "line points:", [(i, float("{:.2f}".format(fit_fn(i)))) for i in range(-2, 2)]
line points: [(-2, -1.2), (-1, -0.6), (0, -0.0), (1, 0.6)]

In [5]:
lse = lambda y, yi: sum([(p-o)**2 for p, o in zip(y, yi)])

2) Least-Squares Error of best-fit regression line

In [6]:
yi =  [float("{:.2f}".format(fit_fn(i))) for i in x]
print "LSE: ", lse(y, yi)
LSE:  6.4

3) Least-squares error of line with slope 1

In [8]:
y_slope_one = x
print "LSE:", lse(y, y_slope_one)
plt.plot(x, y, 'yo', x, y_slope_one, "x--")
plt.xlim(-3, 3);plt.ylim(-3, 3);plt.grid();plt.legend();plt.show()
LSE: 8


Wed Nov 19 23:10:23 EST 2014

By: A.Aziz Altowayan