User:Elgreengeeto/Python Perceptron
Jump to navigation
Jump to search
#a dot product is the sum of the products of aligned-elements from two
#same-lengthed arrays
def dot_product(a, b):
sum = 0
i = 0
while i < len(a):
sum += a[i] * b[i]
i += 1
return sum
class Perceptron:
#percieve method takes three boolean inputs
def percieve(self, ip1, ip2, ip3):
#get the dot product of those inputs and the associated input's weights
sum = dot_product([ip1, ip2, ip3],[self.ip1_weight, self.ip2_weight, self.ip3_weight])
#return the boolean evaulation of whether or not that sum is greater than
#or equal to the perceptron's threshhold
return ( sum >= self.threshhold )
#learn method compares output of percieve() to the expected output
def learn(self, ip1, ip2, ip3, expected):
#if output is less than expected increment the weights of
#_non-null_ inputs by 0.1 (the weights applied to null inputs do not affect
#output so we can't know if those weights were right or wrong)
if self.percieve(ip1, ip2, ip3) < expected:
if ip1:
self.ip1_weight += self.learn_rate
print self.ip1_weight
if ip2:
self.ip2_weight += self.learn_rate
print self.ip2_weight
if ip3:
self.ip3_weight += self.learn_rate
print self.ip3_weight
#if less than expected decrement by 0.1
elif self.percieve(ip1, ip2, ip3) > expected:
if ip1:
self.ip1_weight -= self.learn_rate
print self.ip1_weight
if ip2:
self.ip2_weight -= self.learn_rate
print self.ip1_weight
if ip3:
self.ip3_weight -= self.learn_rate
print self.ip1_weight
#this defines how a Perceptron object represents itself in the interpreter
def __str__(self):
return "Weights: %s, %s, %s. Threshhold: %s. Learn rate: %s." % (self.ip1_weight, self.ip2_weight, self.ip3_weight, self.threshhold, self.learn_rate)
#same as above
__repr__ = __str__
#defines initial values for a new Perceptron object
def __init__(self):
self.ip1_weight = 0.0
self.ip2_weight = 0.0
self.ip3_weight = 0.0
self.threshhold = 0.5
self.learn_rate = 0.1
#trains a perceptron according to data, where data is a list of lists in the
#form [[boolean_value_1,boolean_value_2,boolean_value_3,expected_boolean_output],...]
def train(data, perceptron):
for case in data:
perceptron.learn(case[0],case[1],case[2], case[3])
#define a dataset to try and train a perceptron into becoming a NAND gate
#(turns out this data set is too small, oh Josh is a tricky teacher!)
data = [[1,0,0,1],[1,0,1,1],[1,1,0,1],[1,1,1,0]]
#do the damned thing
if __name__ == '__main__':
subject = Perceptron()
for i in range(1000):
train(data, subject)