Guest User

Untitled

a guest
May 20th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. <?php
  2.  
  3. class Perceptron {
  4.  
  5. protected $learnRate;
  6. protected $synapseWeight = array();
  7. protected $biaWeight;
  8.  
  9. public static function factory($learnRate = 0.6) {
  10. return new static($learnRate);
  11. }
  12.  
  13. public function __construct($learnRate = 0.6) {
  14. $this->learnRate = $learnRate;
  15. }
  16.  
  17. protected function learnFunction($oldWeight, $errorValue, $value) {
  18. return $oldWeight + ($errorValue * $value * $this->learnRate);
  19. }
  20.  
  21. protected function setSynapseWeight($synapse, $weight) {
  22. $this->synapseWeight[$synapse] = $weight;
  23. }
  24.  
  25. protected function synapseWeight($synapse, $inicialize = 0) {
  26. if (!isset($this->synapseWeight[$synapse]))
  27. $this->synapseWeight[$synapse] = $inicialize;
  28. return $this->synapseWeight[$synapse];
  29. }
  30.  
  31. public function process(Array $values) {
  32. $sum = 1 * $this->biaWeight;
  33.  
  34. foreach ($values as $key => $value)
  35. $sum += $this->synapseWeight($key) * $value;
  36.  
  37. return $sum > 0.5 ? 1 : 0;
  38. }
  39.  
  40. public function forceLearn(Array $values, $learn) {
  41. while ($this->learn($values, $learn));
  42. return $this;
  43. }
  44.  
  45. public function learn(Array $values, $learn) {
  46. if (($ret = $this->process($values)) == $learn)
  47. return false;
  48.  
  49. $errorValue = $learn - $ret;
  50.  
  51. $this->biaWeight = $this->
  52. learnFunction($this->biaWeight, $errorValue, 1);
  53.  
  54. foreach ($values as $key => $value)
  55. $this->setSynapseWeight($key,
  56. $this->learnFunction($this->synapseWeight($key),
  57. $errorValue, $value));
  58.  
  59. return true;
  60. }
  61.  
  62. }
Add Comment
Please, Sign In to add comment