-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnipals.js
88 lines (77 loc) · 2.25 KB
/
nipals.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
import { isAnyArray } from './indexIsAnyArray.js';
import Matrix from './matrix.js';
import WrapperMatrix2D from './WrapperMatrix2D.js';
export default class nipals {
constructor(X, options = {}) {
X = WrapperMatrix2D.checkMatrix(X);
let { Y } = options;
const {
scaleScores = false,
maxIterations = 1000,
terminationCriteria = 1e-10,
} = options;
let u;
if (Y) {
if (isAnyArray(Y) && typeof Y[0] === 'number') {
Y = Matrix.columnVector(Y);
} else {
Y = WrapperMatrix2D.checkMatrix(Y);
}
if (Y.rows !== X.rows) {
throw new Error('Y should have the same number of rows as X');
}
u = Y.getColumnVector(0);
} else {
u = X.getColumnVector(0);
}
let diff = 1;
let t, q, w, tOld;
for (
let counter = 0;
counter < maxIterations && diff > terminationCriteria;
counter++
) {
w = X.transpose().mmul(u).div(u.transpose().mmul(u).get(0, 0));
w = w.div(w.norm());
t = X.mmul(w).div(w.transpose().mmul(w).get(0, 0));
if (counter > 0) {
diff = t.clone().sub(tOld).pow(2).sum();
}
tOld = t.clone();
if (Y) {
q = Y.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));
q = q.div(q.norm());
u = Y.mmul(q).div(q.transpose().mmul(q).get(0, 0));
} else {
u = t;
}
}
if (Y) {
let p = X.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));
p = p.div(p.norm());
let xResidual = X.clone().sub(t.clone().mmul(p.transpose()));
let residual = u.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));
let yResidual = Y.clone().sub(
t.clone().mulS(residual.get(0, 0)).mmul(q.transpose()),
);
this.t = t;
this.p = p.transpose();
this.w = w.transpose();
this.q = q;
this.u = u;
this.s = t.transpose().mmul(t);
this.xResidual = xResidual;
this.yResidual = yResidual;
this.betas = residual;
} else {
this.w = w.transpose();
this.s = t.transpose().mmul(t).sqrt();
if (scaleScores) {
this.t = t.clone().div(this.s.get(0, 0));
} else {
this.t = t;
}
this.xResidual = X.sub(t.mmul(w.transpose()));
}
}
}