-
Notifications
You must be signed in to change notification settings - Fork 0
/
nn.js
99 lines (84 loc) · 1.96 KB
/
nn.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
class NeuralNetwork {
constructor(a, b, c, d) {
if (a instanceof tf.Sequential) {
this.input_nodes = b;
this.hidden_nodes = c;
this.output_nodes = d;
this.model = a;
} else {
this.input_nodes = a;
this.hidden_nodes = b;
this.output_nodes = c;
this.model = this.createModel();
}
}
createModel() {
return tf.sequential({
layers: [
tf.layers.dense({
inputShape: [this.input_nodes],
units: this.hidden_nodes,
activation: "sigmoid"
}),
tf.layers.dense({
units: this.hidden_nodes,
activation: "sigmoid"
}),
tf.layers.dense({
units: this.output_nodes,
activation: "relu"
})
]
});
}
predict(input) {
return tf.tidy(() => {
let tf_xs = tf.tensor2d([input]);
let output = this.model.predict(tf_xs).dataSync();
let max = -1;
let maxIndex = -1;
for (let i = 0; i < output.length; i++) {
if (output[i] > max) {
max = output[i];
maxIndex = i;
}
}
return maxIndex;
});
}
copy() {
return tf.tidy(() => {
let modelCopy = this.createModel();
let modelWeights = this.model.getWeights();
let weightCopies = [];
for (let i = 0; i < modelWeights.length; i++) {
weightCopies[i] = modelWeights[i].clone();
}
modelCopy.setWeights(weightCopies);
return new NeuralNetwork(modelCopy, this.input_nodes, this.hidden_nodes, this.output_nodes);
});
}
mutate(rate) {
tf.tidy(() => {
let weights = this.model.getWeights();
let mutatedWeights = [];
for (let i = 0; i < weights.length; i++) {
let tensor = weights[i];
let shape = weights[i].shape;
let values = tensor.dataSync().slice();
for (let j = 0; j < values.length; j++) {
if (random(1) < rate) {
let w = values[j];
values[i] = w + randomGaussian();
}
}
let newTensor = tf.tensor(values, shape);
mutatedWeights[i] = newTensor;
}
this.model.setWeights(mutatedWeights);
});
}
dispose() {
this.model.dispose();
}
}