In [5]:
%matplotlib inline
import matplotlib
import autograd.numpy as np
import matplotlib.pyplot as plt
import random
import math
from autograd import grad
def generateChevronData():
xBounds = [-50, 50]
yBounds = [-50, 50]
totalPoints = 100
points = []
targets = []
for i in range(0, totalPoints):
x = random.randint(xBounds[0], xBounds[1])
y = random.randint(yBounds[0], yBounds[1])
if x >= y and x <= -y:
points.append([1, x/50.0,y/50.0])
targets.append(0)
else:
points.append([1, x/50.0,y/50.0])
targets.append(1)
return np.array(points), np.array(targets)
def plotScatter(points):
xs = [x[1] for x in points]
ys = [y[2] for y in points]
plt.scatter(xs, ys)
In [6]:
def sigmoid(phi):
return 1.0/(1.0 + np.exp(-phi))
def MSE(weights):
predictions = logisticPrediction(weights, points)
return 1.0/2.0 * np.sum(np.power((targets - predictions), 2))
def logisticPrediction(weights, p):
ins = np.array(list(map(lambda x: predict(weights, x), p)))
return ins
def predict(weights, i):
wp = np.array([-weights[2] + weights[0] * weights[1], -weights[0], 1])
return sigmoid(np.dot(wp, i))
# return sigmoid(-((weights[2] - i[2]) + weights[0] * (i[1] - weights[1])))
In [7]:
def computeGradient(weights, example, target):
prediction = predict(weights, example)
dE_dO = computeErrorDifferential(prediction, target)
dO_dZ = prediction * (1-prediction)
dZ_dy = -1
dZ_dm = -(example[1] - weights[1])
dZ_dx = weights[0]
dE_dZ = dE_dO * dO_dZ
grad = np.zeros(3)#[0.0, 0.0, 0.0]
grad[0] = dZ_dm * dE_dZ
grad[1] = dZ_dx * dE_dZ
grad[2] = dZ_dy * dE_dZ
return grad
def computeErrorDifferential(prediction, target):
return -(target - prediction)
In [8]:
def trainBoundaryHunter():
weights = np.array([0.0, 0.0, 0.0])
# trainingGradient = grad(MSE)
print("Initial Loss: ", MSE(weights))
for i in range(0, 10000):
# g = trainingGradient(weights) * 0.01
weights = computeStep(weights)
# weights -= g
if i % 1000 == 0:
print("Loss [i = " + str(i) + "]: " + str(MSE(weights)))
print(weights)
print("Trained Loss: ", MSE(weights))
print("Weights: ", weights)
return weights
def computeStep(weights):
totalG = np.zeros(3)
for i in range(0, len(points)):
g = computeGradient(weights, points[i], targets[i])
totalG += g
# totalG = totalG * (1/len(points))
weights -= totalG * 0.01
return weights
In [9]:
random.seed(1234)
points, targets = generateChevronData()
plt.axis([-1.5, 1.5, -1.5, 1.5])
# Plot points on graph
c1 = []
c2 = []
for i in range(0, len(points)):
if targets[i] == 0:
c1.append(points[i])
else:
c2.append(points[i])
print("Type 0: ", len(c1))
print("Type 1: ", len(c2))
plotScatter(c1)
plotScatter(c2)
weights = trainBoundaryHunter()
byas = 1 * (weights[2] + weights[0] * weights[1])
Xcoef = 1 * weights[0]
plt.plot([-1.0, 1.0], [-1*Xcoef + byas, Xcoef + byas], 'k-')
plt.scatter(weights[1], weights[2])
plt.plot([-1.0, 1.0], [weights[2] + weights[0]*((-1) - weights[1]), weights[2] + weights[0]*(1 - weights[1])], 'k-')
plt.gca().set_aspect('equal')
plt.show()
In [ ]:
In [ ]:
In [ ]: