Skip to content

Instantly share code, notes, and snippets.

@danielmoralesp
Created July 1, 2019 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielmoralesp/411384c9f3fa79bde3fd5e497e4c0c69 to your computer and use it in GitHub Desktop.
Save danielmoralesp/411384c9f3fa79bde3fd5e497e4c0c69 to your computer and use it in GitHub Desktop.
perceptron.py
lines = []
class Perceptron:
def __init__(self, num_inputs=3, weights=[1,1,1]):
self.num_inputs = num_inputs
self.weights = weights
def weighted_sum(self, inputs):
weighted_sum = 0
for i in range(self.num_inputs):
weighted_sum += self.weights[i]*inputs[i]
return weighted_sum
def activation(self, weighted_sum):
if weighted_sum >= 0:
return 1
if weighted_sum < 0:
return -1
def training(self, training_set):
foundLine = False
while not foundLine:
total_error = 0
for inputs in training_set:
prediction = self.activation(self.weighted_sum(inputs))
actual = training_set[inputs]
error = actual - prediction
total_error += abs(error)
for i in range(self.num_inputs):
self.weights[i] += error*inputs[i]
slope = -self.weights[0]/self.weights[1]
intercept = -self.weights[2]/self.weights[1]
y1 = (slope * 0) + intercept
y2 = (slope * 50) + intercept
lines.append([[0,50], [y1, y2]])
if total_error == 0:
foundLine = True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment