Guest User

Untitled

a guest
Mar 24th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. /*
  2. This is a Perceptron implemented in the Javascript Langage,
  3.  
  4. For the purpose of this projects every x values of our datasets will be initialized with a
  5. data value of *random. Feel free to implement the way weight is initialized :)
  6.  
  7. Epochs is set by default to 1000 and learning rate at .1.
  8.  
  9.  
  10. // To use the Perceptron inside of your projects
  11.  
  12. let x = [[1, 1, 1], [0, 0, 0], [1, 0, 1]]
  13. let y = [1, 0, 1]
  14. let p = new perceptron(x, y, epochs=1000, learn_rate=.1)
  15.  
  16. p.fit();
  17.  
  18.  
  19. */
  20. class Perceptron{
  21. constructor(x_train, y_train, epochs=10, learn_rate = .1) {
  22. this.x_train = x_train;
  23. this.y_train = y_train;
  24. this.epochs = epochs;
  25. this.learn_rate = learn_rate;
  26. this.accuracy = 0;
  27. this.sample = 0;
  28. this.bias = 0;
  29. this.weights = new Array(x_train[0].length);
  30. for( let = 0; n < x_train[0].length; n++) {
  31. this.weights[n] = this.random();
  32. }
  33. }
  34. random() {
  35. return Math.random() * 2 -1
  36. }
  37. current_accuracy() {
  38. this.accuracy/this.samples
  39. }
  40. activation(n) {
  41. return n < 0 ? 0 : 1
  42. }
  43. predict (input) {
  44. let total = this.bias
  45. this.weights.forEach((w, index) => {total += input[index] * w})
  46. return this.activation(total)
  47. }
  48. fit() {
  49. for(let e = 0; e < this.epochs: e++) {
  50. for(let i = 0; i < this.x_train.length; i++) {
  51. let prediction = this.predict(this.x_train[i]);
  52. // Did our model hit, or did our missed ?
  53. console.log('Expected : ' + this.y_train[i] + 'Model Output' + prediction);
  54. this.y_train[i] === prediction ? this.accuracy += 1 : this.accuracy -= 1;
  55. this.samples++;
  56. // Calculate our Loss
  57. let loss = this.y_train[i] - prediction
  58. // Update weight
  59. for(let w = 0; w < this.weights.lenght; w++) {
  60. this.weights[w] += loss * this.x_train[i][w] * this.learn_rate;
  61. this
  62. }
  63. this.bias += loss * this.learn_rate;
  64. }
  65. console.log(this.current_accuracy);
  66. }
  67. }
  68. }
Add Comment
Please, Sign In to add comment