tyrion

perceptron.py

Oct 30th, 2014
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.96 KB | None | 0 0
  1. from collections import namedtuple
  2.  
  3.  
  4. Input = namedtuple('Input', ['index', 'value'])
  5.  
  6. def identity(x):
  7.     return x
  8.  
  9. def step(x):
  10.     return 1 if x >= 0 else -1
  11.  
  12.  
  13. class OutputNeuron:
  14.  
  15.     def __init__(self, weights, fn=identity):
  16.         self.order = len(weights)
  17.         self.weights = weights
  18.         self.inputs = [0] * self.order
  19.         self.fn = fn
  20.  
  21.     def activate(self, input):
  22.         self.inputs[input.index] = input.value
  23.         return self.activate_next()
  24.  
  25.     def activate_many(self, inputs):
  26.         for i, value in inputs:
  27.             self.inputs[i] = value
  28.         return self.activate_next()
  29.  
  30.     def activate_all(self, inputs):
  31.         self.inputs = list(inputs)
  32.         return self.activate_next()
  33.  
  34.     def activate_next(self):
  35.         return self.compute()
  36.  
  37.     def compute(self):
  38.         return self.fn(sum(map(lambda x,y: x*y, self.weights, self.inputs)))
  39.  
  40.     def train(self, table, h):
  41.         print('Train')
  42.  
  43.         error = False
  44.         for inputs, output in table.items():
  45.             y = self.activate_all(inputs)
  46.             print(self.weights, inputs, y, output)
  47.             if y != output:
  48.                 error = True
  49.                 for i in range(self.order):
  50.                     self.weights[i] += h * inputs[i] * output
  51.  
  52.         if error:
  53.             self.train(table, h)
  54.  
  55.     def __repr__(self):
  56.         return 'Neuron I:{} O:{}'.format(self.inputs, self.compute())
  57.  
  58.  
  59. class Neuron(OutputNeuron):
  60.  
  61.     def __init__(self, weights, synapsis, fn=identity):
  62.         super().__init__(weights, fn)
  63.         self.output = synapsis
  64.  
  65.     def activate_next(self):
  66.         input = Input(self.output.index, self.compute())
  67.         return self.output.neuron.activate(input)
  68.  
  69.  
  70. if __name__ == '__main__':
  71.     n = OutputNeuron([0, 0, 0], step)
  72.     print(n)
  73.     table = {
  74.         (1, -1, -1): -1,
  75.         (1, -1, 1): -1,
  76.         (1, 1, -1): -1,
  77.         (1, 1, 1): 1
  78.     }
  79.     n.train(table, 0.5)
  80.     print(n)
Advertisement
Add Comment
Please, Sign In to add comment