Created
May 10, 2022 09:54
-
-
Save agorushkin/4a68ad3785364787288bd8bde87ddc8e 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
| export class Network { | |
| #weights = [] as number[]; | |
| #bias = 0; | |
| #alpha = 0.1; | |
| constructor(alpha: number, size: number) { | |
| this.#alpha = alpha | |
| this.#weights = new Array(size).fill(0).map(() => Math.random() * 2 - 1); | |
| } | |
| predict(input: number[]) { | |
| return this.#weights.reduce((acc, w, i) => acc + w * input[i], this.#bias) > 0 ? 1 : 0 | |
| } | |
| train(data: { input: number[], output: number }[], epochs = 1) { | |
| for (let epoch = 0; epoch < epochs; epoch++) { | |
| for (const { input, output } of data) { | |
| const prediction = this.predict(input); | |
| this.#weights = this.#weights.map((w, i) => w + this.#alpha * (output - prediction) * input[i]); | |
| this.#bias += this.#alpha * (output - prediction); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment