neuron.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import random
  2. import math
  3. class Neuron(object):
  4. """
  5. An abstract class describe how to implement a Neuron
  6. """
  7. def __init__(self, nb_inputs=1, bias=1):
  8. """
  9. Define how many inputs a neuron owns
  10. """
  11. # Arbitrary chosen
  12. self.learning_control = 0.01
  13. # Bias
  14. self.bias = bias
  15. # set inputs
  16. self.setNbInputs(nb_inputs=nb_inputs)
  17. def setNbInputs(self, nb_inputs):
  18. """
  19. Set the neuron number of inputs
  20. """
  21. # At first ways weights are initialized to random values
  22. self.weights = [round(random.uniform(-1.0, 1.0), 3) for weight in range(nb_inputs)]
  23. def activate(self, inputs_sum):
  24. """
  25. Abstract activate function trigger an answer following inputs and assiociated weights
  26. """
  27. raise NotImplementedError
  28. def feedforward(self, inputs):
  29. """
  30. Allows to send data using inputs part
  31. Returns the output
  32. """
  33. processed_inputs = inputs[:]
  34. inputs_sum = sum([input_value * self.weights[i] for i, input_value in enumerate(processed_inputs)])
  35. return self.activate(inputs_sum)
  36. class Perceptron(Neuron):
  37. """
  38. Simplest neuron possible, only output 1 or 0, following a threshold
  39. """
  40. def __init__(self, nb_inputs=1, bias=1):
  41. """
  42. Create a Perceptron
  43. """
  44. Neuron.__init__(self, nb_inputs=nb_inputs, bias=bias)
  45. def activate(self, inputs_sum):
  46. """
  47. A step function, X < T => 0 or X => T => 1
  48. """
  49. return 1 if inputs_sum + self.bias > 0 else 0
  50. class Sigmoid(Neuron):
  51. """
  52. Sigmoid neuron, its output is less suggestible than perceptron
  53. allowing to learn more easily
  54. """
  55. def __init__(self, nb_inputs=1, bias=1):
  56. """
  57. Create a Sigmoid
  58. """
  59. Neuron.__init__(self, nb_inputs=nb_inputs, bias=bias)
  60. def __sigmoid(x):
  61. return 1/float(1 + math.exp(-x))
  62. def activate(self, inputs_sum):
  63. """
  64. A step function, X < T => 0 or X => T => 1
  65. """
  66. return self.__sigmoid(inputs_sum + self.bias)