Skip to content

Instantly share code, notes, and snippets.

@amogh112
Created March 8, 2020 05:02
Show Gist options
  • Save amogh112/ba93061a53d4511fcb136adaa0a91a5a to your computer and use it in GitHub Desktop.
Save amogh112/ba93061a53d4511fcb136adaa0a91a5a to your computer and use it in GitHub Desktop.
import numpy as np
def generateData(a, b, num_samples):
data_x = np.random.uniform(a, b, num_samples)
data_y = np.random.uniform(a, b, num_samples)
data = np.array(list(zip(data_x, data_y)))
labels = np.array([-1 if datap[0] <= datap[1] else 1 for datap in data])
return data, labels
def evaluate(datap, weights):
result = datap @ weights.T
if result > 0:
return 1
else:
return -1
def trainPerceptron(max_iter, data, labels,hinge=False):
weights = np.zeros(2)
bias = np.zeros(1)
for i in range(max_iter):
for i, x in enumerate(data):
if hinge:
act = (x @ weights.T) + bias[0]
else:
act = (x @ weights.T)
y = labels[i]
if y * act <= 0:
weights = weights + y * x
bias = bias + y
return weights, bias
def predictPerceptron(weights, bias, x, hinge):
if hinge:
act = x @ weights.T + bias
else:
act = x @ weights.T
result = np.ones_like(act)
result[np.where(act <= 0)] = -1
return result
def mainPerceptron(hinge):
# hinge = False
x, y = generateData(0, 1, 20)
weights, bias = trainPerceptron(1000, x, y, hinge)
import matplotlib.pyplot as plt
for i,dp in enumerate(x):
if y[i] == 1:
plt.scatter(*dp, color='orange')
else:
plt.scatter(*dp, color='blue')
# plt.show()
test_x, test_y = generateData(0, 1, 1000)
result = predictPerceptron(weights,bias,test_x,hinge)
correct = np.sum(result == test_y)
accuracy = correct/test_y.shape[0]
print(accuracy)
if __name__ == "__main__":
for i in range(20):
mainPerceptron(hinge=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment