In [1]:
import numpy as np

In [145]:
result


Out[145]:
(array([ 1.14995271]), array([[ 0.09264036]]))

In [144]:
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit as curve_fit

def f(x, a):
    return a*x

N = 100
x = np.random.uniform(-1, 1, [N, 2])
y = np.sin(np.pi * x)

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.scatter(0, 0, s=30, c='k')
ax1.scatter(x, y, s=5, c='b', marker='+')

x_limits = [-1, 1]
y_limits = [-1, 1]

sum_slope = 0
sum_bias_error = 0
sum_variance_error = 0

slope = slope if slope else 1.43
for i in range(N):

    xi = x[i]
    yi = y[i]

    result = curve_fit(f, xi, yi)
    slope = result[0][0]
    sum_slope += slope
    
    sum_bias_error += np.square(best_slope* xi - yi).sum() / len(xi)
    sum_variance_error += np.square((slope - best_slope) * xi).sum() / len(xi)
    
    p = [ slope * _ for _ in x_limits]
    ax1.plot(x_limits, p, 'g:')

    ax1.scatter(xi, yi, s=50, c='r')


ax1.set_ylim(x_limits)
ax1.set_xlim(y_limits)

best_slope = sum_slope/N
variance_error = sum_variance_error/N
bias_error = sum_bias_error/N
print ('y = %s * x' % str(best_slope))
print ('bias error = %s' % str(bias_error))
print ('variance error = %s' % str(variance_error))

plt.show()


y = 1.38721099191 * x
bias error = 0.477373354347
variance error = 0.40982404484

In [ ]: