Davids perceptron.pl
Jump to navigation
Jump to search
#!/usr/bin/env python
__author__ = "David Stainton"
__license__ = "Apache License"
import sys
class perceptron(object):
def __init__(self, values):
self.weight = []
self.threshold = .5
self.learning_rate = .1
for value in values:
self.weight.append(value)
def is_success_train_input(self, values, expected):
sum = dot_product(values, self.weight)
if sum == self.threshold:
output = 0
if sum < self.threshold:
output = 0
if sum > self.threshold:
output = 1
if output != expected:
for elk in range(0,len(values)):
if values[elk] == 1:
change = (expected - output) * self.learning_rate
#print "%s %s" % (elk, change)
self.weight[elk] += change
return False
return True
def display(self):
print(self.weight)
def dot_product(a, b):
sum = 0
i = 0
while i < len(a):
sum += a[i] * b[i]
i += 1
return sum
def main():
# initialize with weight values...
p = perceptron([0.0,0.0])
# single values corresponding to expected results for each training input
expect = [1,0,1,1]
# training set
input = [[1,1], [0,0], [0,1], [1,0]]
# try to expose our perceptron to the training set 10 times
repeat = 10
for c in range(0,repeat):
results = []
for elk in range(len(expect)):
results.append(p.is_success_train_input(input[elk], expect[elk]))
p.display()
if False not in results:
return
p.display()
if __name__ == "__main__":
main()