@numero-uno-jpn/rstats 1.8.0 → 1.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/README.ja.md +7 -6
- package/README.md +6 -5
- package/dist/chunks/chunk-3QUOB47N.js +2 -0
- package/dist/chunks/{chunk-73IRLCTF.js → chunk-5PVS6TF2.js} +2 -2
- package/dist/chunks/chunk-6BDTLUNM.js +2 -0
- package/dist/chunks/{chunk-YD4U3QZ3.js → chunk-6U2ICRN3.js} +1 -1
- package/dist/chunks/chunk-6Y7OKIIM.js +2 -0
- package/dist/chunks/chunk-AQ7H4RJH.js +2 -0
- package/dist/chunks/{chunk-3DO726WZ.js → chunk-CN5D6ITZ.js} +2 -2
- package/dist/chunks/{chunk-V7ECXPWY.js → chunk-DC2FP6ZH.js} +2 -2
- package/dist/chunks/{chunk-IJST2ZGT.js → chunk-EDHAQHB7.js} +1 -1
- package/dist/chunks/chunk-F232C4SB.js +3 -0
- package/dist/chunks/{chunk-7ODUCEGX.js → chunk-F3WMBL5R.js} +2 -2
- package/dist/chunks/{chunk-QQHF5T2A.js → chunk-F5K2UXKW.js} +1 -1
- package/dist/chunks/{chunk-YT62DNDS.js → chunk-GYLFMAD6.js} +2 -2
- package/dist/chunks/{chunk-JXJDCQYE.js → chunk-IFFGJN5L.js} +2 -2
- package/dist/chunks/{chunk-TUL6UFLQ.js → chunk-ISNGTKVZ.js} +2 -2
- package/dist/chunks/chunk-JPQEOHZG.js +2 -0
- package/dist/chunks/{chunk-2ZQ2TSZS.js → chunk-JRMISESC.js} +2 -2
- package/dist/chunks/{chunk-LZB43TUL.js → chunk-K25FNCFH.js} +2 -2
- package/dist/chunks/{chunk-D3LKPD4H.js → chunk-KGDCQ2RV.js} +2 -2
- package/dist/chunks/{chunk-TYMC2D5I.js → chunk-LQWAHXHZ.js} +2 -2
- package/dist/chunks/{chunk-TQM6KGKT.js → chunk-MBQJWNPX.js} +2 -2
- package/dist/chunks/chunk-MULNGWZY.js +2 -0
- package/dist/chunks/{chunk-2X6PE6JF.js → chunk-MVIBJA2I.js} +2 -2
- package/dist/chunks/chunk-NAUAW5TO.js +2 -0
- package/dist/chunks/{chunk-RWZ6ICYN.js → chunk-NMVFSSEZ.js} +2 -2
- package/dist/chunks/{chunk-45HUI3M4.js → chunk-NNJGXB5K.js} +2 -2
- package/dist/chunks/{chunk-52RWDNO6.js → chunk-OQFZKQVT.js} +2 -2
- package/dist/chunks/chunk-OXYMJNVJ.js +2 -0
- package/dist/chunks/chunk-PJ73WRSA.js +2 -0
- package/dist/chunks/chunk-R5BXUEH3.js +2 -0
- package/dist/chunks/chunk-RPEFV4FR.js +2 -0
- package/dist/chunks/chunk-T3XFVWOW.js +2 -0
- package/dist/chunks/{chunk-GRTQ7FYQ.js → chunk-Y5M7NEJ5.js} +2 -2
- package/dist/chunks/chunk-Y7SXBQZY.js +2 -0
- package/dist/chunks/chunk-YCBQQHCB.js +2 -0
- package/dist/chunks/{chunk-JIAFWEED.js → chunk-YGKM6PIJ.js} +2 -2
- package/dist/chunks/{chunk-DG2RTNIR.js → chunk-ZUHBIFAJ.js} +2 -2
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/multivariate.d.ts +7 -0
- package/dist/entries/multivariate.js +8 -0
- package/dist/entries/tests.d.ts +3 -1
- package/dist/entries/tests.js +3 -1
- package/dist/htest/grubbs.d.ts +68 -0
- package/dist/htest/grubbs.js +151 -0
- package/dist/htest/multipleComparisons.d.ts +21 -0
- package/dist/htest/multipleComparisons.js +47 -0
- package/dist/htest/rankTests.d.ts +35 -0
- package/dist/htest/rankTests.js +89 -1
- package/dist/internal/summary.js +8 -2
- package/dist/linalg/symmetricLeading.d.ts +8 -0
- package/dist/linalg/symmetricLeading.js +231 -0
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +2 -2
- package/dist/multivariate/cancor.d.ts +55 -0
- package/dist/multivariate/cancor.js +167 -0
- package/dist/multivariate/cmdscale.d.ts +40 -0
- package/dist/multivariate/cmdscale.js +171 -0
- package/dist/multivariate/dist.d.ts +63 -0
- package/dist/multivariate/dist.js +218 -0
- package/dist/multivariate/hclust.d.ts +58 -0
- package/dist/multivariate/hclust.js +264 -0
- package/dist/multivariate/kmeans.d.ts +58 -0
- package/dist/multivariate/kmeans.js +392 -0
- package/dist/multivariate/lda.d.ts +146 -0
- package/dist/multivariate/lda.js +325 -0
- package/dist/multivariate/manova.d.ts +106 -0
- package/dist/multivariate/manova.js +303 -0
- package/dist/multivariate.js +2 -0
- package/dist/numerics.js +2 -2
- package/dist/regression.js +2 -2
- package/dist/rstats.js +16 -16
- package/dist/special.js +2 -2
- package/dist/tests.js +15 -15
- package/llms.txt +4 -1
- package/package.json +6 -1
- package/dist/chunks/chunk-53OM63EU.js +0 -2
- package/dist/chunks/chunk-ANZUXEMH.js +0 -3
- package/dist/chunks/chunk-BHQGMZTI.js +0 -2
- package/dist/chunks/chunk-HXYH5ZMB.js +0 -2
- package/dist/chunks/chunk-HYJ4MIZE.js +0 -2
- package/dist/chunks/chunk-MLNWWGGE.js +0 -2
- package/dist/chunks/chunk-VB6PVRSN.js +0 -2
- package/dist/chunks/chunk-Y4KNH43T.js +0 -2
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
// K-means clustering: batch Lloyd/Forgy, online MacQueen, and point-transfer Hartigan-Wong.
|
|
2
|
+
import { sampleInt } from "../random/sample.js";
|
|
3
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
4
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
5
|
+
const KMEANS_KEYS = ["algorithm", "iterMax", "nstart"];
|
|
6
|
+
function readData(x) {
|
|
7
|
+
if (Array.isArray(x)) {
|
|
8
|
+
if (x.length === 0)
|
|
9
|
+
throw new RangeError("x must be a non-empty numeric matrix");
|
|
10
|
+
if (!Array.isArray(x[0]))
|
|
11
|
+
return { rows: x.map((v) => [Number(v)]), rowNames: null, colNames: null };
|
|
12
|
+
const raw = x;
|
|
13
|
+
const p = raw[0].length;
|
|
14
|
+
if (p === 0 || raw.some((r) => r.length !== p))
|
|
15
|
+
throw new RangeError("x must be a non-empty matrix with equal row lengths");
|
|
16
|
+
return { rows: raw.map((r) => r.map(Number)), rowNames: null, colNames: null };
|
|
17
|
+
}
|
|
18
|
+
if (typeof x === "object" && x !== null) {
|
|
19
|
+
const table = x;
|
|
20
|
+
if (Array.isArray(table.values)) {
|
|
21
|
+
const raw = table.values;
|
|
22
|
+
const p = raw[0]?.length ?? 0;
|
|
23
|
+
if (p === 0 || raw.some((r) => r.length !== p))
|
|
24
|
+
throw new RangeError("x must be a non-empty matrix with equal row lengths");
|
|
25
|
+
return { rows: raw.map((r) => r.map(Number)), rowNames: table.rows ?? null, colNames: table.cols ?? null };
|
|
26
|
+
}
|
|
27
|
+
const cols = Object.entries(x);
|
|
28
|
+
if (cols.length === 0)
|
|
29
|
+
throw new RangeError("x must have at least one column");
|
|
30
|
+
const n = cols[0][1].length;
|
|
31
|
+
if (cols.some(([, v]) => v.length !== n))
|
|
32
|
+
throw new RangeError("columns must have equal lengths");
|
|
33
|
+
return { rows: Array.from({ length: n }, (_, i) => cols.map(([, v]) => Number(v[i]))), rowNames: null,
|
|
34
|
+
colNames: cols.map(([name]) => name) };
|
|
35
|
+
}
|
|
36
|
+
throw new TypeError("x must be a numeric vector, matrix, or data frame");
|
|
37
|
+
}
|
|
38
|
+
function sameRow(a, b) {
|
|
39
|
+
return a.length === b.length && a.every((v, i) => Object.is(v, b[i]));
|
|
40
|
+
}
|
|
41
|
+
function squared(a, b) {
|
|
42
|
+
let s = 0;
|
|
43
|
+
for (let j = 0; j < a.length; j++) {
|
|
44
|
+
const d = a[j] - b[j];
|
|
45
|
+
s += d * d;
|
|
46
|
+
}
|
|
47
|
+
return s;
|
|
48
|
+
}
|
|
49
|
+
function nearest(row, centers) {
|
|
50
|
+
let best = 0, value = squared(row, centers[0]);
|
|
51
|
+
for (let j = 1; j < centers.length; j++) {
|
|
52
|
+
const d = squared(row, centers[j]);
|
|
53
|
+
if (d < value) {
|
|
54
|
+
best = j;
|
|
55
|
+
value = d;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return best;
|
|
59
|
+
}
|
|
60
|
+
function means(rows, cluster, k, p) {
|
|
61
|
+
const centers = Array.from({ length: k }, () => new Array(p).fill(0));
|
|
62
|
+
const size = new Array(k).fill(0);
|
|
63
|
+
for (let i = 0; i < rows.length; i++) {
|
|
64
|
+
const g = cluster[i];
|
|
65
|
+
size[g] = size[g] + 1;
|
|
66
|
+
for (let j = 0; j < p; j++)
|
|
67
|
+
centers[g][j] = centers[g][j] + rows[i][j];
|
|
68
|
+
}
|
|
69
|
+
for (let g = 0; g < k; g++)
|
|
70
|
+
if (size[g] > 0) {
|
|
71
|
+
for (let j = 0; j < p; j++)
|
|
72
|
+
centers[g][j] = centers[g][j] / size[g];
|
|
73
|
+
}
|
|
74
|
+
return { centers, size };
|
|
75
|
+
}
|
|
76
|
+
function totalSS(rows, p) {
|
|
77
|
+
const center = new Array(p).fill(0);
|
|
78
|
+
for (const row of rows)
|
|
79
|
+
for (let j = 0; j < p; j++)
|
|
80
|
+
center[j] = center[j] + row[j];
|
|
81
|
+
for (let j = 0; j < p; j++)
|
|
82
|
+
center[j] = center[j] / rows.length;
|
|
83
|
+
let sum = 0;
|
|
84
|
+
for (const row of rows)
|
|
85
|
+
sum += squared(row, center);
|
|
86
|
+
return sum;
|
|
87
|
+
}
|
|
88
|
+
function fitStats(rows, cluster, k, colNames, rowNames, iter, ifault, warnings) {
|
|
89
|
+
const p = rows[0].length;
|
|
90
|
+
const { centers, size } = means(rows, cluster, k, p);
|
|
91
|
+
// R reports the center of an empty cluster as NaN (the mean of no rows; kmeans_empty_Lloyd)
|
|
92
|
+
for (let g = 0; g < k; g++)
|
|
93
|
+
if (size[g] === 0)
|
|
94
|
+
centers[g] = new Array(p).fill(NaN);
|
|
95
|
+
const withinss = new Array(k).fill(0);
|
|
96
|
+
for (let i = 0; i < rows.length; i++)
|
|
97
|
+
withinss[cluster[i]] += squared(rows[i], centers[cluster[i]]);
|
|
98
|
+
const totss = totalSS(rows, p);
|
|
99
|
+
const totWithinss = withinss.reduce((a, b) => a + b, 0);
|
|
100
|
+
const out = { cluster: cluster.map((v) => v + 1), centers: {
|
|
101
|
+
rows: Array.from({ length: k }, (_, i) => String(i + 1)), cols: colNames, values: centers,
|
|
102
|
+
}, totss, withinss, totWithinss, betweenss: totss - totWithinss, size, iter, ifault, warnings };
|
|
103
|
+
if (rowNames !== null)
|
|
104
|
+
out.names = [...rowNames];
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
function lloyd(rows, initial, iterMax) {
|
|
108
|
+
// Batch updates: assign every row to its nearest center, stop when no assignment changed, else move each nonempty
|
|
109
|
+
// center to its mean. R counts the assignment passes (the last one confirms convergence) and reports
|
|
110
|
+
// iter.max + 1 when it stops at the limit (kmeans_iter_Lloyd_1..5, kmeans_vector_Lloyd)
|
|
111
|
+
const k = initial.length;
|
|
112
|
+
const centers = initial.map((r) => [...r]);
|
|
113
|
+
let cluster = new Array(rows.length).fill(-1);
|
|
114
|
+
for (let iter = 1; iter <= iterMax; iter++) {
|
|
115
|
+
const next = rows.map((row) => nearest(row, centers));
|
|
116
|
+
const changed = next.some((v, i) => v !== cluster[i]);
|
|
117
|
+
cluster = next;
|
|
118
|
+
if (!changed)
|
|
119
|
+
return { cluster, iter, converged: true };
|
|
120
|
+
const stats = means(rows, cluster, k, rows[0].length);
|
|
121
|
+
for (let g = 0; g < k; g++)
|
|
122
|
+
if (stats.size[g] > 0)
|
|
123
|
+
centers[g] = stats.centers[g];
|
|
124
|
+
}
|
|
125
|
+
return { cluster, iter: iterMax + 1, converged: false };
|
|
126
|
+
}
|
|
127
|
+
function macqueen(rows, initial, iterMax) {
|
|
128
|
+
const k = initial.length, p = rows[0].length;
|
|
129
|
+
let cluster = rows.map((row) => nearest(row, initial));
|
|
130
|
+
const { centers, size } = means(rows, cluster, k, p);
|
|
131
|
+
// an empty cluster keeps its initial center (R: kmeans_empty_MacQueen), not the mean of no rows
|
|
132
|
+
for (let g = 0; g < k; g++)
|
|
133
|
+
if (size[g] === 0)
|
|
134
|
+
centers[g] = [...initial[g]];
|
|
135
|
+
let converged = false, iter = 0;
|
|
136
|
+
for (let pass = 0; pass < iterMax; pass++) {
|
|
137
|
+
let moved = false;
|
|
138
|
+
// MacQueen's sequential update: each transfer changes the two means and
|
|
139
|
+
// their counts immediately, so subsequent observations see the new fit.
|
|
140
|
+
for (let i = 0; i < rows.length; i++) {
|
|
141
|
+
const from = cluster[i];
|
|
142
|
+
if (size[from] <= 1)
|
|
143
|
+
continue;
|
|
144
|
+
const to = nearest(rows[i], centers);
|
|
145
|
+
if (to === from)
|
|
146
|
+
continue;
|
|
147
|
+
const row = rows[i];
|
|
148
|
+
const oldN = size[from], newN = size[to];
|
|
149
|
+
for (let j = 0; j < p; j++) {
|
|
150
|
+
centers[from][j] = (oldN * centers[from][j] - row[j]) / (oldN - 1);
|
|
151
|
+
centers[to][j] = (newN * centers[to][j] + row[j]) / (newN + 1);
|
|
152
|
+
}
|
|
153
|
+
size[from] = oldN - 1;
|
|
154
|
+
size[to] = newN + 1;
|
|
155
|
+
cluster[i] = to;
|
|
156
|
+
moved = true;
|
|
157
|
+
}
|
|
158
|
+
iter = pass + 1;
|
|
159
|
+
if (!moved) {
|
|
160
|
+
converged = true;
|
|
161
|
+
break;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return { cluster, iter: converged ? iter : iterMax + 1, converged };
|
|
165
|
+
}
|
|
166
|
+
function hartiganWong(rows, initial, iterMax) {
|
|
167
|
+
// Hartigan & Wong (1979), from the paper's description (not from AS 136's code): an optimal-transfer stage over a
|
|
168
|
+
// live set of clusters, then a quick-transfer stage between each point's closest and second-closest clusters,
|
|
169
|
+
// repeated until an optimal-transfer pass moves nothing. iter counts the optimal-transfer passes; R reports
|
|
170
|
+
// iter.max + 1 at the limit (kmeans_iter_Hartigan-Wong_1..5)
|
|
171
|
+
const n = rows.length, k = initial.length, p = rows[0].length;
|
|
172
|
+
const ic1 = new Array(n), ic2 = new Array(n);
|
|
173
|
+
for (let i = 0; i < n; i++) {
|
|
174
|
+
let b1 = 0, b2 = 1, d1 = squared(rows[i], initial[0]), d2 = squared(rows[i], initial[1]);
|
|
175
|
+
if (d2 < d1) {
|
|
176
|
+
[b1, b2, d1, d2] = [1, 0, d2, d1];
|
|
177
|
+
}
|
|
178
|
+
for (let g = 2; g < k; g++) {
|
|
179
|
+
const d = squared(rows[i], initial[g]);
|
|
180
|
+
if (d < d1) {
|
|
181
|
+
b2 = b1;
|
|
182
|
+
d2 = d1;
|
|
183
|
+
b1 = g;
|
|
184
|
+
d1 = d;
|
|
185
|
+
}
|
|
186
|
+
else if (d < d2) {
|
|
187
|
+
b2 = g;
|
|
188
|
+
d2 = d;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
ic1[i] = b1;
|
|
192
|
+
ic2[i] = b2;
|
|
193
|
+
}
|
|
194
|
+
const { centers, size } = means(rows, ic1, k, p);
|
|
195
|
+
if (size.some((v) => v === 0))
|
|
196
|
+
throw new RangeError("empty cluster: try a better set of initial centers");
|
|
197
|
+
const move = (i, from, to) => {
|
|
198
|
+
const row = rows[i], oldN = size[from], newN = size[to];
|
|
199
|
+
for (let j = 0; j < p; j++) {
|
|
200
|
+
centers[from][j] = (oldN * centers[from][j] - row[j]) / (oldN - 1);
|
|
201
|
+
centers[to][j] = (newN * centers[to][j] + row[j]) / (newN + 1);
|
|
202
|
+
}
|
|
203
|
+
size[from] = oldN - 1;
|
|
204
|
+
size[to] = newN + 1;
|
|
205
|
+
ic1[i] = to;
|
|
206
|
+
ic2[i] = from;
|
|
207
|
+
};
|
|
208
|
+
const removeCost = (i, g) => size[g] / (size[g] - 1) * squared(rows[i], centers[g]);
|
|
209
|
+
const addCost = (i, g) => size[g] / (size[g] + 1) * squared(rows[i], centers[g]);
|
|
210
|
+
// live set: cluster g is live at optimal-transfer step t when it was updated within the last n steps
|
|
211
|
+
const updated = new Array(k).fill(0);
|
|
212
|
+
let t = 0;
|
|
213
|
+
for (let iter = 1; iter <= iterMax; iter++) {
|
|
214
|
+
let moved = false;
|
|
215
|
+
for (let i = 0; i < n; i++) {
|
|
216
|
+
t++;
|
|
217
|
+
const l1 = ic1[i];
|
|
218
|
+
if (size[l1] === 1)
|
|
219
|
+
continue;
|
|
220
|
+
const live = (g) => updated[g] >= t - n;
|
|
221
|
+
const l1Live = live(l1);
|
|
222
|
+
let best = ic2[i], bestCost = addCost(i, best);
|
|
223
|
+
for (let g = 0; g < k; g++) {
|
|
224
|
+
if (g === l1 || g === ic2[i] || !(l1Live || live(g)))
|
|
225
|
+
continue;
|
|
226
|
+
const c = addCost(i, g);
|
|
227
|
+
if (c < bestCost) {
|
|
228
|
+
best = g;
|
|
229
|
+
bestCost = c;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
if (bestCost < removeCost(i, l1)) {
|
|
233
|
+
move(i, l1, best);
|
|
234
|
+
updated[l1] = t;
|
|
235
|
+
updated[best] = t;
|
|
236
|
+
moved = true;
|
|
237
|
+
}
|
|
238
|
+
else
|
|
239
|
+
ic2[i] = best;
|
|
240
|
+
}
|
|
241
|
+
if (!moved)
|
|
242
|
+
return { cluster: ic1, iter, converged: true };
|
|
243
|
+
// quick transfer: until n consecutive steps move nothing
|
|
244
|
+
let quiet = 0;
|
|
245
|
+
for (let i = 0; quiet < n; i = (i + 1) % n) {
|
|
246
|
+
const l1 = ic1[i], l2 = ic2[i];
|
|
247
|
+
if (size[l1] > 1 && addCost(i, l2) < removeCost(i, l1)) {
|
|
248
|
+
move(i, l1, l2);
|
|
249
|
+
updated[l1] = t;
|
|
250
|
+
updated[l2] = t;
|
|
251
|
+
quiet = 0;
|
|
252
|
+
}
|
|
253
|
+
else
|
|
254
|
+
quiet++;
|
|
255
|
+
}
|
|
256
|
+
// with two clusters the quick-transfer stage has tried every transfer: no need to return to the optimal-transfer
|
|
257
|
+
// stage (Hartigan & Wong 1979; kmeans_equal_best_seed_*)
|
|
258
|
+
if (k === 2)
|
|
259
|
+
return { cluster: ic1, iter, converged: true };
|
|
260
|
+
}
|
|
261
|
+
return { cluster: ic1, iter: iterMax + 1, converged: false };
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* K-means clustering by the Hartigan-Wong, Lloyd, Forgy or MacQueen algorithm.
|
|
265
|
+
* Equivalent to R's `kmeans()`.
|
|
266
|
+
* @category Multivariate analysis
|
|
267
|
+
*/
|
|
268
|
+
export function kmeans(x, centersInput, options = {}) {
|
|
269
|
+
checkOptions(options, KMEANS_KEYS, "kmeans"); // generated: option-keys.mjs
|
|
270
|
+
const data = readData(x);
|
|
271
|
+
const rows = data.rows, n = rows.length, p = rows[0]?.length ?? 0;
|
|
272
|
+
if (n < 1 || p < 1 || rows.some((r) => r.length !== p))
|
|
273
|
+
throw new RangeError("x must be a non-empty matrix");
|
|
274
|
+
if (rows.some((r) => r.some((v) => !Number.isFinite(v))))
|
|
275
|
+
throw new RangeError("NA/NaN/Inf in foreign function call (arg 1)");
|
|
276
|
+
const algorithms = ["Hartigan-Wong", "Lloyd", "Forgy", "MacQueen"];
|
|
277
|
+
const requested = options.algorithm ?? "Hartigan-Wong";
|
|
278
|
+
const matches = algorithms.filter((v) => v.startsWith(requested));
|
|
279
|
+
if (matches.length !== 1)
|
|
280
|
+
throw new RangeError("invalid algorithm");
|
|
281
|
+
const algorithm = matches[0];
|
|
282
|
+
const iterMax = options.iterMax ?? 10;
|
|
283
|
+
if (!Number.isFinite(iterMax) || iterMax < 1)
|
|
284
|
+
throw new RangeError("'iter.max' must be positive");
|
|
285
|
+
const maxIterations = Math.trunc(iterMax);
|
|
286
|
+
const nstart = Math.max(1, Math.trunc(options.nstart ?? 1));
|
|
287
|
+
let initialSets = [];
|
|
288
|
+
if (typeof centersInput === "number") {
|
|
289
|
+
const k = Math.trunc(centersInput);
|
|
290
|
+
if (k < 1 || k > n)
|
|
291
|
+
throw new RangeError("centers must be between 1 and nrow(x)");
|
|
292
|
+
const distinct = new Set(rows.map((r) => JSON.stringify(r))).size;
|
|
293
|
+
if (k > distinct)
|
|
294
|
+
throw new RangeError("more cluster centers than distinct data points.");
|
|
295
|
+
// R's first start (kmeans_dup_start_seed_1..12, checked by the random state afterwards): k rows by
|
|
296
|
+
// sample.int(nrow, k); when those rows are not distinct, one draw of k rows from the distinct rows (in order of
|
|
297
|
+
// first appearance)
|
|
298
|
+
const unique = [];
|
|
299
|
+
const seen = new Set();
|
|
300
|
+
for (const r of rows) {
|
|
301
|
+
const key = JSON.stringify(r);
|
|
302
|
+
if (!seen.has(key)) {
|
|
303
|
+
seen.add(key);
|
|
304
|
+
unique.push(r);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
const draw = () => {
|
|
308
|
+
let chosen = sampleInt(n, { size: k }).map((i) => [...rows[i]]);
|
|
309
|
+
if (new Set(chosen.map((r) => JSON.stringify(r))).size !== k) {
|
|
310
|
+
chosen = sampleInt(unique.length, { size: k }).map((i) => [...unique[i]]);
|
|
311
|
+
}
|
|
312
|
+
return chosen;
|
|
313
|
+
};
|
|
314
|
+
// with nstart >= 2 every start draws k of the distinct rows (kmeans_equal_best_dup_seed_1..8 and
|
|
315
|
+
// experiments/cluster110-nstart-rng.json: the random state after nstart = 2..5 for 8 seeds)
|
|
316
|
+
if (nstart === 1)
|
|
317
|
+
initialSets.push(draw());
|
|
318
|
+
else
|
|
319
|
+
for (let start = 0; start < nstart; start++) {
|
|
320
|
+
initialSets.push(sampleInt(unique.length, { size: k }).map((i) => [...unique[i]]));
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
else {
|
|
324
|
+
const initial = centersInput.length > 0 && typeof centersInput[0] === "number"
|
|
325
|
+
? centersInput.map((v) => [Number(v)])
|
|
326
|
+
: centersInput.map((r) => Array.from(r, Number));
|
|
327
|
+
if (initial.length < 1 || initial.some((r) => r.length !== p))
|
|
328
|
+
throw new RangeError("must have same number of columns in 'x' and 'centers'");
|
|
329
|
+
if (initial.some((r) => r.some((v) => !Number.isFinite(v))))
|
|
330
|
+
throw new RangeError("initial centers must be finite");
|
|
331
|
+
for (let i = 0; i < initial.length; i++)
|
|
332
|
+
for (let j = 0; j < i; j++) {
|
|
333
|
+
if (sameRow(initial[i], initial[j]))
|
|
334
|
+
throw new RangeError("initial centers are not distinct");
|
|
335
|
+
}
|
|
336
|
+
initialSets = [initial];
|
|
337
|
+
}
|
|
338
|
+
const k = initialSets[0].length;
|
|
339
|
+
if (algorithm === "Hartigan-Wong" && k === n)
|
|
340
|
+
throw new RangeError("number of cluster centres must lie between 1 and nrow(x)");
|
|
341
|
+
// Normalize only extreme magnitudes before computing squared distances. This keeps assignments and
|
|
342
|
+
// center updates scale-equivariant when squaring would overflow or underflow; ordinary inputs keep
|
|
343
|
+
// the exact arithmetic path used by the R fixtures. Starts are selected above from the original rows,
|
|
344
|
+
// so this transformation does not alter the random stream or duplicate-row decisions.
|
|
345
|
+
let magnitude = 0;
|
|
346
|
+
for (const row of rows)
|
|
347
|
+
for (const value of row)
|
|
348
|
+
magnitude = Math.max(magnitude, Math.abs(value));
|
|
349
|
+
for (const initial of initialSets)
|
|
350
|
+
for (const row of initial)
|
|
351
|
+
for (const value of row)
|
|
352
|
+
magnitude = Math.max(magnitude, Math.abs(value));
|
|
353
|
+
const rescale = magnitude > 2 ** 512 || (magnitude > 0 && magnitude < 2 ** -512);
|
|
354
|
+
const workRows = rescale ? rows.map((row) => row.map((value) => value / magnitude)) : rows;
|
|
355
|
+
const workInitialSets = rescale ? initialSets.map((set) => set.map((row) => row.map((value) => value / magnitude))) : initialSets;
|
|
356
|
+
let best = null;
|
|
357
|
+
let bestW = Infinity;
|
|
358
|
+
let anyNotConverged = false;
|
|
359
|
+
for (const initial of workInitialSets) {
|
|
360
|
+
// One cluster: R does no iteration (iter 1, ifault NULL for every algorithm; kmeans_k1_*)
|
|
361
|
+
const result = k === 1 ? { cluster: new Array(n).fill(0), iter: 1, converged: true }
|
|
362
|
+
: algorithm === "Hartigan-Wong" ? hartiganWong(workRows, initial, maxIterations)
|
|
363
|
+
: algorithm === "MacQueen" ? macqueen(workRows, initial, maxIterations) : lloyd(workRows, initial, maxIterations);
|
|
364
|
+
const warnings = [];
|
|
365
|
+
const stats = means(workRows, result.cluster, k, p);
|
|
366
|
+
if (stats.size.some((v) => v === 0)) {
|
|
367
|
+
if (algorithm === "Hartigan-Wong")
|
|
368
|
+
throw new RangeError("empty cluster: try a better set of initial centers");
|
|
369
|
+
warnings.push("empty cluster: try a better set of initial centers", "empty cluster: try a better set of initial centers");
|
|
370
|
+
}
|
|
371
|
+
if (!result.converged)
|
|
372
|
+
anyNotConverged = true;
|
|
373
|
+
const fit = fitStats(workRows, result.cluster, k, data.colNames, data.rowNames, result.iter, algorithm === "Hartigan-Wong" && k > 1 ? (result.converged ? 0 : 2) : (result.converged ? null : 2), warnings);
|
|
374
|
+
if (fit.totWithinss < bestW) {
|
|
375
|
+
best = fit;
|
|
376
|
+
bestW = fit.totWithinss;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
// Return centers and sums of squares on the caller's original scale.
|
|
380
|
+
if (rescale) {
|
|
381
|
+
const restoreSquare = (value) => value === 0 ? 0 : (value * magnitude) * magnitude;
|
|
382
|
+
best.centers.values = best.centers.values.map((row) => row.map((value) => value * magnitude));
|
|
383
|
+
best.totss = restoreSquare(best.totss);
|
|
384
|
+
best.withinss = best.withinss.map(restoreSquare);
|
|
385
|
+
best.totWithinss = restoreSquare(best.totWithinss);
|
|
386
|
+
best.betweenss = restoreSquare(best.betweenss);
|
|
387
|
+
}
|
|
388
|
+
// R warns once when any start stopped at iter.max, even when the kept start converged (kmeans_seed_nstart_lloyd)
|
|
389
|
+
if (anyNotConverged)
|
|
390
|
+
best.warnings.push(`did not converge in ${maxIterations} ${maxIterations === 1 ? "iteration" : "iterations"}`);
|
|
391
|
+
return best;
|
|
392
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { type VectorOrMatrix } from "../linalg/matrix.js";
|
|
2
|
+
import { type GroupLabel } from "../htest/groups.js";
|
|
3
|
+
import type { DataFrame } from "../models/modelFrame.js";
|
|
4
|
+
/** Options for LDA fitting.
|
|
5
|
+
* @category Multivariate analysis
|
|
6
|
+
*/
|
|
7
|
+
export interface LdaOptions {
|
|
8
|
+
/** Fitting method; only "moment" is supported. Default "moment". */
|
|
9
|
+
method?: "moment" | string;
|
|
10
|
+
/** Prior class probabilities, in class-level order. Defaults to observed class proportions. */
|
|
11
|
+
prior?: readonly number[];
|
|
12
|
+
/** Numerical tolerance for rank determination and within-class covariance calculations. Default 1e-4. */
|
|
13
|
+
tol?: number;
|
|
14
|
+
/** Return leave-one-out cross-validation predictions instead of a fitted model. Default false. */
|
|
15
|
+
CV?: boolean;
|
|
16
|
+
/** Names for predictor columns in matrix input. */
|
|
17
|
+
xNames?: readonly string[];
|
|
18
|
+
/** Declared class levels; unused levels remain in `lev` and produce warnings. */
|
|
19
|
+
groupLevels?: readonly GroupLabel[];
|
|
20
|
+
/** Explicit factor levels for formula variables. */
|
|
21
|
+
levels?: Record<string, readonly string[]>;
|
|
22
|
+
}
|
|
23
|
+
/** Options for LDA prediction.
|
|
24
|
+
* @category Multivariate analysis
|
|
25
|
+
*/
|
|
26
|
+
export interface LdaPredictionOptions {
|
|
27
|
+
/** Prediction method; only "plug-in" is supported. Default "plug-in". */
|
|
28
|
+
method?: "plug-in" | string;
|
|
29
|
+
/** New predictor rows; omitted to predict the observations used to fit the model. */
|
|
30
|
+
newdata?: VectorOrMatrix;
|
|
31
|
+
/** Prior class probabilities for this prediction. Defaults to the fitted priors. */
|
|
32
|
+
prior?: readonly number[];
|
|
33
|
+
/** Number of discriminant score dimensions to return. Defaults to all available dimensions. */
|
|
34
|
+
dimen?: number;
|
|
35
|
+
}
|
|
36
|
+
/** A labelled LDA result matrix.
|
|
37
|
+
* @category Multivariate analysis
|
|
38
|
+
*/
|
|
39
|
+
export interface LdaTable {
|
|
40
|
+
/** Row labels, or null when rows are observations without labels. */
|
|
41
|
+
rows: string[] | null;
|
|
42
|
+
/** Column labels, or null when columns are not named. */
|
|
43
|
+
cols: string[] | null;
|
|
44
|
+
/** Numeric matrix entries in row-major order. */
|
|
45
|
+
values: number[][];
|
|
46
|
+
}
|
|
47
|
+
/** A fitted linear discriminant model.
|
|
48
|
+
* @category Multivariate analysis
|
|
49
|
+
*/
|
|
50
|
+
export interface LdaFit {
|
|
51
|
+
/** Prior class probabilities in the order of `lev`. */
|
|
52
|
+
prior: number[];
|
|
53
|
+
/** Number of training observations in each class. */
|
|
54
|
+
counts: number[];
|
|
55
|
+
/** Class means, with classes in rows and predictors in columns. */
|
|
56
|
+
means: LdaTable;
|
|
57
|
+
/** Metric-normalised discriminant directions, with predictors in rows and dimensions in columns. */
|
|
58
|
+
scaling: LdaTable;
|
|
59
|
+
/** Singular values associated with the discriminant dimensions. */
|
|
60
|
+
svd: number[];
|
|
61
|
+
/** Number of observations used to fit the model. */
|
|
62
|
+
N: number;
|
|
63
|
+
/** Class labels in prediction and prior order. */
|
|
64
|
+
lev: string[];
|
|
65
|
+
/** Warnings produced while fitting the model. */
|
|
66
|
+
warnings: string[];
|
|
67
|
+
/** @internal Unscaled class means retained for prediction. */
|
|
68
|
+
_means: number[][];
|
|
69
|
+
/** @internal Class labels with non-empty training observations. */
|
|
70
|
+
_activeLev: string[];
|
|
71
|
+
/** @internal Prior-weighted center of the predictor columns. */
|
|
72
|
+
_center: number[];
|
|
73
|
+
/** @internal Internal discriminant directions in scaled predictor coordinates. */
|
|
74
|
+
_scaling: number[][];
|
|
75
|
+
/** @internal Inverse pooled within-class covariance matrix. */
|
|
76
|
+
_covInverse: number[][];
|
|
77
|
+
/** @internal Predictor scale factors used internally. */
|
|
78
|
+
_scale: number[];
|
|
79
|
+
/** @internal Column origins in coordinates divided by `_scale`. */
|
|
80
|
+
_origin: number[];
|
|
81
|
+
/** @internal Column spread factors after removing a dominant offset. */
|
|
82
|
+
_spread: number[];
|
|
83
|
+
/** @internal Scaled training predictor matrix. */
|
|
84
|
+
_x: number[][];
|
|
85
|
+
/** @internal Predictor column names. */
|
|
86
|
+
_xNames: string[];
|
|
87
|
+
/** @internal Rank tolerance used to fit the model. */
|
|
88
|
+
_tol: number;
|
|
89
|
+
}
|
|
90
|
+
/** Plug-in prediction from an LDA fit.
|
|
91
|
+
* @category Multivariate analysis
|
|
92
|
+
*/
|
|
93
|
+
export interface LdaPrediction {
|
|
94
|
+
/** Predicted class label for each observation. */
|
|
95
|
+
class: string[];
|
|
96
|
+
/** Posterior class probabilities, with classes in columns. */
|
|
97
|
+
posterior: LdaTable;
|
|
98
|
+
/** Discriminant scores for each observation. */
|
|
99
|
+
x: LdaTable;
|
|
100
|
+
}
|
|
101
|
+
/** Leave-one-out LDA predictions.
|
|
102
|
+
* @category Multivariate analysis
|
|
103
|
+
*/
|
|
104
|
+
export interface LdaCVResult {
|
|
105
|
+
/** Leave-one-out predicted class label for each training observation. */
|
|
106
|
+
class: string[];
|
|
107
|
+
/** Leave-one-out posterior class probabilities, with classes in columns. */
|
|
108
|
+
posterior: LdaTable;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Linear discriminant analysis (moment method). Equivalent to R's `MASS::lda()`. The moment method only. Supports matrix/group and formula/data-frame inputs.
|
|
112
|
+
* Directions are metric-normalised and their signs are deterministic.
|
|
113
|
+
*
|
|
114
|
+
* @param x Predictor matrix.
|
|
115
|
+
* @param grouping Class labels.
|
|
116
|
+
* @param options Prior probabilities, tolerance, and leave-one-out CV.
|
|
117
|
+
* @category Multivariate analysis
|
|
118
|
+
*/
|
|
119
|
+
export declare function lda(x: VectorOrMatrix, grouping: readonly GroupLabel[], options?: LdaOptions & {
|
|
120
|
+
CV?: false;
|
|
121
|
+
}): LdaFit;
|
|
122
|
+
/** Leave-one-out cross-validation result overload. */
|
|
123
|
+
export declare function lda(x: VectorOrMatrix, grouping: readonly GroupLabel[], options: LdaOptions & {
|
|
124
|
+
CV: true;
|
|
125
|
+
}): LdaCVResult;
|
|
126
|
+
/**
|
|
127
|
+
* Linear discriminant analysis from a formula, e.g. `"class ~ x1 + x2"` or `"class ~ ."`.
|
|
128
|
+
*
|
|
129
|
+
* @param formula Formula.
|
|
130
|
+
* @param data Data frame.
|
|
131
|
+
* @param options Prior probabilities, tolerance, and leave-one-out CV.
|
|
132
|
+
*/
|
|
133
|
+
export declare function lda(formula: string, data: DataFrame, options?: LdaOptions & {
|
|
134
|
+
CV?: false;
|
|
135
|
+
}): LdaFit;
|
|
136
|
+
export declare function lda(formula: string, data: DataFrame, options: LdaOptions & {
|
|
137
|
+
CV: true;
|
|
138
|
+
}): LdaCVResult;
|
|
139
|
+
/**
|
|
140
|
+
* Plug-in prediction for a fitted {@link lda} model. Equivalent to R's `predict.lda()`. The plug-in method only.
|
|
141
|
+
*
|
|
142
|
+
* @param fit A fitted LDA model.
|
|
143
|
+
* @param options New observations, prior override, and number of discriminant scores.
|
|
144
|
+
* @category Multivariate analysis
|
|
145
|
+
*/
|
|
146
|
+
export declare function ldaPredict(fit: LdaFit, options?: LdaPredictionOptions): LdaPrediction;
|