Neural Network


SUBMITTED BY: Guest

DATE: May 19, 2013, 1:24 a.m.

FORMAT: Python

SIZE: 2.0 kB

HITS: 2616

  1. class ANN:
  2. def __init__(self):
  3. self.neurons = list()
  4. self.synapses = dict()
  5. def synapsesAt(self, neuron_id):
  6. if self.synapses.has_key(neuron_id):
  7. return self.synapses[neuron_id]
  8. return {}
  9. def valueAt(self, neuron_id):
  10. #print '-->', self.neurons[neuron_id]
  11. return self.neurons[neuron_id].output()
  12. def addNeuron(self, number_of=1):
  13. for i in range(number_of):
  14. neuron_id = len(self.neurons)
  15. neuron = Neuron(neuron_id, self)
  16. self.neurons.append(neuron)
  17. def addSynapse(self, dest_neuron, source_neuron, weight):
  18. if not self.synapses.has_key(source_neuron.id):
  19. self.synapses[source_neuron.id] = dict()
  20. self.synapses[source_neuron.id][dest_neuron.id] = weight
  21. class Neuron:
  22. def __init__(self, neuron_id, Ann, is_input=False, value=1):
  23. self.id = neuron_id
  24. self.Ann = Ann
  25. self.is_input = is_input
  26. self.value = value
  27. def output(self):
  28. if self.is_input:
  29. #print 'neuron is input, overrides to', self.value
  30. return self.value
  31. sigma = 0
  32. synapses = self.Ann.synapsesAt(self.id)
  33. for synapse_id in synapses:
  34. #print 'processing synapse', synapse_id
  35. sigma += self.Ann.valueAt(synapse_id) * synapses[synapse_id]
  36. return sigma
  37. def setValue(self, value):
  38. self.value = value
  39. ann = ANN()
  40. ann.addNeuron(4)
  41. n = ann.neurons
  42. n[0].is_input = True
  43. n[1].is_input = True
  44. ann.addSynapse(n[0], n[2], 1)
  45. ann.addSynapse(n[0], n[3], 1)
  46. ann.addSynapse(n[1], n[2], 1)
  47. ann.addSynapse(n[1], n[3], 1)
  48. print 'neuron', n[2].id, 'outputs value of' , n[2].output()
  49. print 'neuron', n[3].id, 'outputs value of' , n[3].output()

comments powered by Disqus