Skip to content

Instantly share code, notes, and snippets.

@agorushkin
Created May 10, 2022 09:54
Show Gist options
  • Select an option

  • Save agorushkin/4a68ad3785364787288bd8bde87ddc8e to your computer and use it in GitHub Desktop.

Select an option

Save agorushkin/4a68ad3785364787288bd8bde87ddc8e to your computer and use it in GitHub Desktop.
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