Advertisement
Guest User

Untitled

a guest
Aug 17th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. const uid = require("cuid");
  2.  
  3. function Neuron() {
  4. this.id = uid(); // ID
  5. this.bias = bias == undefined ? Math.random() * 2 - 1 : bias; // this.bias ∈ ℝ && -1 < this.bias < 1
  6.  
  7. // Incoming Connections
  8. this.incoming = {
  9. neurons: {}, // new Map()
  10. weights: {} // new Map()
  11. }
  12. // Outgoing Connections
  13. this.outgoing = {
  14. neurons: {}, // new Map()
  15. weights: {} // new Map()
  16. }
  17.  
  18. this._output; // f'(x)
  19. this.output; // f(x)
  20. this.error; // E'(f(x))
  21.  
  22. this.connect = function(neuron, weight) {
  23. this.outgoing.neurons[neuron.id] = neuron;
  24. neuron.incoming.neurons[this.id] = this;
  25. this.outgoing.weights[neuron.id] = neuron.incoming.weights[this.id] = weight == undefined ? Math.random() * 2 - 1 : weight; // weight ∈ ℝ && -1 < weight < 1
  26. }
  27.  
  28. this.activate = function(input) {
  29. const self = this;
  30.  
  31. function sigmoid(x) { return 1 / (1 + Math.exp(-x)) } // f(x) = 1 / (1 + e^(-x))
  32. function _sigmoid(x) { return sigmoid(x) * (1 - sigmoid(x)) } // f'(x) = f(x) * (1 - f(x))
  33.  
  34. // Input Neurons
  35. if(input) {
  36. this._output = 1; // f'(x)
  37. this.output = input; // f(x)
  38. }
  39. // Hidden/Output Neurons
  40. else {
  41. // Σ (x • w)
  42. const sum = Object.keys(this.incoming.targets).reduce(function(total, target, index) {
  43. return total += self.incoming.targets[target].output * self.incoming.weights[target];
  44. }, this.bias);
  45.  
  46. this._output = _sigmoid(sum); // f'(x)
  47. this.output = sigmoid(sum); // f(x)
  48. }
  49.  
  50. return this.output;
  51. }
  52. }
  53.  
  54. module.exports = Neuron;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement