/
taf.js
54 lines (48 loc) · 1.14 KB
/
taf.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
import Layer from './base.js'
/**
* Trainable AF layer
*/
export default class TrainableAFLayer extends Layer {
/**
* @param {object} config config
* @param {number} [config.a] a
* @param {number} [config.b] b
*/
constructor({ a = 0, b = 0, ...rest }) {
super(rest)
this._a = a
this._b = b
}
calc(x) {
this._i = x
const o = x.copy()
o.map(v => Math.sqrt((v - this._a) ** 2 + this._b ** 2))
return o
}
grad(bo) {
this._bo = bo
const bi = bo.copy()
bi.broadcastOperate(this._i, (a, b) => (a * (b - this._a)) / Math.sqrt((b - this._a) ** 2 + this._b ** 2))
return bi
}
update(optimizer) {
let sa = 0
let sb = 0
for (let i = 0; i < this._i.length; i++) {
sa +=
this._bo.value[i] *
((this._a - this._i.value[i]) / Math.sqrt((this._i.value[i] - this._a) ** 2 + this._b ** 2))
sb += this._bo.value[i] * (this._b / Math.sqrt((this._i.value[i] - this._a) ** 2 + this._b ** 2))
}
this._a -= optimizer.delta('a', sa / this._i.length)
this._b -= optimizer.delta('b', sb / this._i.length)
}
toObject() {
return {
type: 'taf',
a: this._a,
b: this._b,
}
}
}
TrainableAFLayer.registLayer('taf')