Created
May 25, 2020 12:16
-
-
Save syusui-s/120ea389651d60fc94425c57d0d1cbce to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const assert = (pred) => { if (! pred) throw new Error("Assertion failed"); }; | |
| class Connection { | |
| constructor(prevs, next) { | |
| if (prevs.length != next.weights.length) { | |
| throw new RangeError("prevs length should be equal to next weights length"); | |
| } | |
| if (! prevs.map(p => p.weights.length).reduce((x, y) => x && x == y ? x : false)) { | |
| throw new RangeError("all perceptron in prevs should have same weights length"); | |
| } | |
| Object.assign(this, { prevs, next }); | |
| } | |
| process(inputs) { | |
| const nextInput = this.prevs.map(p => p.process(inputs)) | |
| const result = this.next.process(nextInput); | |
| return result; | |
| } | |
| } | |
| class Perceptron { | |
| constructor(bias, weights) { | |
| Object.assign(this, { weights, bias }); | |
| } | |
| process(inputs) { | |
| if (inputs.length != this.weights.length) { | |
| throw new RangeError(`inputs length should equal to weights (weights: ${this.weights.length}, inputs: ${inputs.length})`); | |
| } | |
| let result = this.bias; | |
| for (let i = 0; i < inputs.length; ++i) { | |
| result += this.weights[i] * inputs[i]; | |
| } | |
| return result > 0 ? 1 : 0; | |
| } | |
| } | |
| const gateAnd = new Perceptron(-.7, [.5, .5]); | |
| assert(gateAnd.process([0, 0]) == 0); | |
| assert(gateAnd.process([0, 1]) == 0); | |
| assert(gateAnd.process([1, 0]) == 0); | |
| assert(gateAnd.process([1, 1]) == 1); | |
| const gateOr = new Perceptron(-.2, [.5, .5]); | |
| assert(gateOr.process([0, 0]) == 0); | |
| assert(gateOr.process([0, 1]) == 1); | |
| assert(gateOr.process([1, 0]) == 1); | |
| assert(gateOr.process([1, 1]) == 1); | |
| const gateNand = new Perceptron(.7, [-.5, -.5]); | |
| assert(gateNand.process([0, 0]) == 1); | |
| assert(gateNand.process([0, 1]) == 1); | |
| assert(gateNand.process([1, 0]) == 1); | |
| assert(gateNand.process([1, 1]) == 0); | |
| const gateXor = new Connection([gateNand, gateOr], gateAnd); | |
| assert(gateXor.process([0, 0]) == 0); | |
| assert(gateXor.process([0, 1]) == 1); | |
| assert(gateXor.process([1, 0]) == 1); | |
| assert(gateXor.process([1, 1]) == 0); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment