import numpy
from matplotlib import pyplot as plt
from random import randint
mean = lambda l : sum(l)/len(l)
def estimate_intercept(X, Y):
assert(len(X) == len(Y))
x_mean = mean(X)
y_mean = mean(Y)
return sum([(x - x_mean) * (y - y_mean) for x, y in zip(X,Y)])/sum([(x - x_mean)**2 for x in X])
def estimate_intercept2(X,Y):
assert(len(X) == len(Y))
return sum([y/x for x, y in zip(X,Y) if x])/len(X)
%matplotlib notebook
f = lambda x : 5*x+randint(-100, 100)
X = list(range(100))
Xt = list(range(300))
Y = list(map(f, X))
m1 = estimate_intercept(X,Y)
m2 = estimate_intercept2(X,Y)
fig = plt.figure()
ax1 = fig.add_subplot(1,2,1)
ax1.scatter(X,Y)
ax1.plot(Xt, list(map(lambda x : m1*x, Xt)), label='m1')
ax1.plot(Xt, list(map(lambda x : m2*x, Xt)), label='m2')
print(m1)
print(m2)
print(m1/m2)
plt.legend()
plt.show()
4.61121512151215 5.865754613447786 0.7861247913338401