In [1]:
# shows how linear classification analysis can be applied to 1-dimensional data
import numpy as np
import matplotlib.pyplot as plt
In [2]:
# load the data
X = []
Y = []
for line in open('ex1data1.txt'):
x, y = line.split(',')
X.append(float(x))
Y.append(float(y))
In [3]:
# let's turn X and Y into numpy arrays since that will be useful later
X = np.array(X)
Y = np.array(Y)
In [4]:
# let's plot the data to see what it looks like
plt.scatter(X,Y)
plt.show()
In [5]:
# apply the equations we learned to calculate a and b
denominator = X.dot(X) - X.mean() * X.sum()
a = ( X.dot(Y) - Y.mean()*X.sum() ) / denominator
b = ( Y.mean() * X.dot(X) - X.mean() * X.dot(Y) ) / denominator
In [6]:
# let's calculate the predicted Y
Yhat = a*X + b
In [7]:
# let's plot everything together to make sure it worked
plt.scatter(X, Y)
plt.plot(X, Yhat)
plt.show()
In [8]:
# determine how good the model is by computing the r-squared
d1 = Y - Yhat
d2 = Y - Y.mean()
r2 = 1 - d1.dot(d1) / d2.dot(d2)
print("the error is:", 1-r2)
In [ ]: