-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
58 lines (44 loc) · 1.58 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
const tf = require('@tensorflow/tfjs')
const ConnectionGene = require('./neat/ConnectionGene')
const NodeGene = require('./neat/NodeGene')
const Genome = require('./neat/Genome')
const Graph = require('./viz/Graph')
const TFGenome = require('./neat/TFGenome')
const Neat = require('./neat/Neat.js')
function main () {
require('./test.js')
document.getElementById('evolve').onclick = evolve
document.getElementById('evolve10').onclick = evolve10
const infoDOM = document.getElementById('info')
const startGen = new Genome()
startGen.addNode(new NodeGene('INPUT', 0))
startGen.addNode(new NodeGene('INPUT', 1))
startGen.addNode(new NodeGene('HIDDEN', 2))
startGen.addNode(new NodeGene('OUTPUT', 3))
startGen.addConnection(0, 2)
startGen.addConnection(1, 2)
startGen.addConnection(2, 3)
const graph = new Graph(startGen)
const neat = new Neat(startGen, (gen) => {
const inputs = [[0, 1, 0, 1], [0, 0, 1, 1]]
const labels = [0, 1, 1, 0]
const outputTensor = TFGenome.toTFGraph(gen, inputs)[0]
const mse = (preds, labels) => preds.sub(labels).square().mean()
const fitness = -mse(outputTensor, tf.tensor(labels)).dataSync()[0]
return fitness
})
function evolve () {
infoDOM.textContent = JSON.stringify(neat.nextGeneration())
graph.update(neat.fittestGenome)
}
function evolve10 () {
let info = ''
for (let i = 0; i < 10; i++) {
info = neat.nextGeneration()
console.log(info)
}
infoDOM.textContent = JSON.stringify(info)
graph.update(neat.fittestGenome)
}
}
document.addEventListener('DOMContentLoaded', main)