-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.html
111 lines (100 loc) · 2.74 KB
/
test.html
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
100
101
102
103
104
105
106
107
108
109
110
111
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
<script>
/**
* @param [object] opts - options:
* {
* [int] input - number of inputs in the input layer
* [array] hidden - array of numbers representing the number
* of nodes in each hidden layer
* [int] output - number of output nodes
* }
*/
function random(min, max) {
return Math.random() * (max - min) + min;
}
class NN {
constructor(opts) {
this.input = opts.input
this.hidden = opts.hidden
this.output = opts.output
this.model = opts.model || this.createModel()
}
createModel() {
let model = tf.sequential()
// creates hidden layers and connects them
for (let i = 0; i < this.hidden.length; i++) {
let layer = tf.layers.dense({
units: this.hidden[i], // number of nodes
inputShape: i === 0 ? [this.input] : [this.hidden[i - 1]],
activation: 'sigmoid'
})
model.add(layer)
}
let output = tf.layers.dense({
units: this.output,
activation: 'softmax'
})
model.add(output)
return model
}
/**
*
* @param {array} vals - array of values to supply the model
*/
predict(vals) {
return tf.tidy(() => {
let inputs = tf.tensor2d([vals])
let prediction = this.model.predict(inputs)
let a = prediction.dataSync()
return a
})
}
copy() {
return tf.tidy(() => {
// create model with the same shape
let modelCopy = this.createModel()
let weights = this.model.getWeights()
weights.map((t) => t.clone())
modelCopy.setWeights(weights)
return new NN({
model: modelCopy,
input: this.input,
hidden: this.hidden,
output: this.output
})
})
}
mutate(rate) {
return tf.tidy(() => {
let copy = this.copy()
let weights = this.model.getWeights()
let newWeights = weights.map(t => {
let shape = t.shape
let weightValues = t.dataSync()
mutatedWeights = weightValues.map(v => {
if (Math.random() < rate) return random(-1, 1)
else return v
})
return tf.tensor(mutatedWeights, shape)
})
this.model.setWeights(newWeights)
})
}
}
let model = new NN({
input: 4,
hidden: [4, 4],
output: 1
})
</script>
</html>