/
ogd.js
72 lines (67 loc) · 1.5 KB
/
ogd.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
/**
* Online gradient descent
*/
export default class OnlineGradientDescent {
// https://olpy.readthedocs.io/en/latest/modules/olpy.classifiers.OGD.html#olpy.classifiers.OGD
/**
* @param {number} [c] Tuning parameter
* @param {'zero_one'} [loss] Loss type name
*/
constructor(c = 1, loss = 'zero_one') {
this._c = c
this._w = null
this._w0 = 0
this._t = 1
if (loss === 'zero_one') {
this._loss = (t, y) => {
return t === y ? 0 : 1
}
}
}
/**
* Update model parameters with one data.
*
* @param {number[]} x Training data
* @param {1 | -1} y Target value
*/
update(x, y) {
const m = Math.sign(this._w.reduce((s, v, d) => s + v * x[d], this._w0))
const loss = this._loss(y, m)
if (loss === 0) return
const c = this._c / Math.sqrt(this._t)
for (let i = 0; i < this._w.length; i++) {
this._w[i] += c * y * x[i]
}
this._w0 += c * y
this._t++
}
/**
* Fit model parameters.
*
* @param {Array<Array<number>>} x Training data
* @param {Array<1 | -1>} y Target values
*/
fit(x, y) {
if (!this._w) {
this._w = Array(x[0].length).fill(0)
this._w0 = 0
}
for (let i = 0; i < x.length; i++) {
this.update(x[i], y[i])
}
}
/**
* Returns predicted datas.
*
* @param {Array<Array<number>>} data Sample data
* @returns {(1 | -1)[]} Predicted values
*/
predict(data) {
const p = []
for (let i = 0; i < data.length; i++) {
const r = data[i].reduce((s, v, d) => s + v * this._w[d], this._w0)
p[i] = r <= 0 ? -1 : 1
}
return p
}
}