-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
AffinityPropagation.ts
504 lines (412 loc) · 15.5 KB
/
AffinityPropagation.ts
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
/* eslint-disable */
/* NOTE: This file is auto-generated. Do not edit it directly. */
import crypto from 'node:crypto'
import { PythonBridge, NDArray, ArrayLike, SparseMatrix } from '@/sklearn/types'
/**
Perform Affinity Propagation Clustering of data.
Read more in the [User Guide](../clustering.html#affinity-propagation).
[Python Reference](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.AffinityPropagation.html)
*/
export class AffinityPropagation {
id: string
opts: any
_py: PythonBridge
_isInitialized: boolean = false
_isDisposed: boolean = false
constructor(opts?: {
/**
Damping factor in the range `\[0.5, 1.0)` is the extent to which the current value is maintained relative to incoming values (weighted 1 - damping). This in order to avoid numerical oscillations when updating these values (messages).
@defaultValue `0.5`
*/
damping?: number
/**
Maximum number of iterations.
@defaultValue `200`
*/
max_iter?: number
/**
Number of iterations with no change in the number of estimated clusters that stops the convergence.
@defaultValue `15`
*/
convergence_iter?: number
/**
Make a copy of input data.
@defaultValue `true`
*/
copy?: boolean
/**
Preferences for each point - points with larger values of preferences are more likely to be chosen as exemplars. The number of exemplars, ie of clusters, is influenced by the input preferences value. If the preferences are not passed as arguments, they will be set to the median of the input similarities.
*/
preference?: ArrayLike | number
/**
Which affinity to use. At the moment ‘precomputed’ and `euclidean` are supported. ‘euclidean’ uses the negative squared euclidean distance between points.
@defaultValue `'euclidean'`
*/
affinity?: 'euclidean' | 'precomputed'
/**
Whether to be verbose.
@defaultValue `false`
*/
verbose?: boolean
/**
Pseudo-random number generator to control the starting state. Use an int for reproducible results across function calls. See the [Glossary](../../glossary.html#term-random_state).
*/
random_state?: number
}) {
this.id = `AffinityPropagation${crypto.randomUUID().split('-')[0]}`
this.opts = opts || {}
}
get py(): PythonBridge {
return this._py
}
set py(pythonBridge: PythonBridge) {
this._py = pythonBridge
}
/**
Initializes the underlying Python resources.
This instance is not usable until the `Promise` returned by `init()` resolves.
*/
async init(py: PythonBridge): Promise<void> {
if (this._isDisposed) {
throw new Error(
'This AffinityPropagation instance has already been disposed'
)
}
if (this._isInitialized) {
return
}
if (!py) {
throw new Error(
'AffinityPropagation.init requires a PythonBridge instance'
)
}
this._py = py
await this._py.ex`
import numpy as np
from sklearn.cluster import AffinityPropagation
try: bridgeAffinityPropagation
except NameError: bridgeAffinityPropagation = {}
`
// set up constructor params
await this._py.ex`ctor_AffinityPropagation = {'damping': ${
this.opts['damping'] ?? undefined
}, 'max_iter': ${this.opts['max_iter'] ?? undefined}, 'convergence_iter': ${
this.opts['convergence_iter'] ?? undefined
}, 'copy': ${this.opts['copy'] ?? undefined}, 'preference': np.array(${
this.opts['preference'] ?? undefined
}) if ${this.opts['preference'] !== undefined} else None, 'affinity': ${
this.opts['affinity'] ?? undefined
}, 'verbose': ${this.opts['verbose'] ?? undefined}, 'random_state': ${
this.opts['random_state'] ?? undefined
}}
ctor_AffinityPropagation = {k: v for k, v in ctor_AffinityPropagation.items() if v is not None}`
await this._py
.ex`bridgeAffinityPropagation[${this.id}] = AffinityPropagation(**ctor_AffinityPropagation)`
this._isInitialized = true
}
/**
Disposes of the underlying Python resources.
Once `dispose()` is called, the instance is no longer usable.
*/
async dispose() {
if (this._isDisposed) {
return
}
if (!this._isInitialized) {
return
}
await this._py.ex`del bridgeAffinityPropagation[${this.id}]`
this._isDisposed = true
}
/**
Fit the clustering from features, or affinity matrix.
*/
async fit(opts: {
/**
Training instances to cluster, or similarities / affinities between instances if `affinity='precomputed'`. If a sparse feature matrix is provided, it will be converted into a sparse `csr\_matrix`.
*/
X?: ArrayLike[]
/**
Not used, present here for API consistency by convention.
*/
y?: any
}): Promise<any> {
if (this._isDisposed) {
throw new Error(
'This AffinityPropagation instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error('AffinityPropagation must call init() before fit()')
}
// set up method params
await this._py.ex`pms_AffinityPropagation_fit = {'X': np.array(${
opts['X'] ?? undefined
}) if ${opts['X'] !== undefined} else None, 'y': ${opts['y'] ?? undefined}}
pms_AffinityPropagation_fit = {k: v for k, v in pms_AffinityPropagation_fit.items() if v is not None}`
// invoke method
await this._py
.ex`res_AffinityPropagation_fit = bridgeAffinityPropagation[${this.id}].fit(**pms_AffinityPropagation_fit)`
// convert the result from python to node.js
return this
._py`res_AffinityPropagation_fit.tolist() if hasattr(res_AffinityPropagation_fit, 'tolist') else res_AffinityPropagation_fit`
}
/**
Fit clustering from features/affinity matrix; return cluster labels.
*/
async fit_predict(opts: {
/**
Training instances to cluster, or similarities / affinities between instances if `affinity='precomputed'`. If a sparse feature matrix is provided, it will be converted into a sparse `csr\_matrix`.
*/
X?: ArrayLike[]
/**
Not used, present here for API consistency by convention.
*/
y?: any
}): Promise<NDArray> {
if (this._isDisposed) {
throw new Error(
'This AffinityPropagation instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error(
'AffinityPropagation must call init() before fit_predict()'
)
}
// set up method params
await this._py.ex`pms_AffinityPropagation_fit_predict = {'X': np.array(${
opts['X'] ?? undefined
}) if ${opts['X'] !== undefined} else None, 'y': ${opts['y'] ?? undefined}}
pms_AffinityPropagation_fit_predict = {k: v for k, v in pms_AffinityPropagation_fit_predict.items() if v is not None}`
// invoke method
await this._py
.ex`res_AffinityPropagation_fit_predict = bridgeAffinityPropagation[${this.id}].fit_predict(**pms_AffinityPropagation_fit_predict)`
// convert the result from python to node.js
return this
._py`res_AffinityPropagation_fit_predict.tolist() if hasattr(res_AffinityPropagation_fit_predict, 'tolist') else res_AffinityPropagation_fit_predict`
}
/**
Get metadata routing of this object.
Please check [User Guide](../../metadata_routing.html#metadata-routing) on how the routing mechanism works.
*/
async get_metadata_routing(opts: {
/**
A [`MetadataRequest`](sklearn.utils.metadata_routing.MetadataRequest.html#sklearn.utils.metadata_routing.MetadataRequest "sklearn.utils.metadata_routing.MetadataRequest") encapsulating routing information.
*/
routing?: any
}): Promise<any> {
if (this._isDisposed) {
throw new Error(
'This AffinityPropagation instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error(
'AffinityPropagation must call init() before get_metadata_routing()'
)
}
// set up method params
await this._py
.ex`pms_AffinityPropagation_get_metadata_routing = {'routing': ${
opts['routing'] ?? undefined
}}
pms_AffinityPropagation_get_metadata_routing = {k: v for k, v in pms_AffinityPropagation_get_metadata_routing.items() if v is not None}`
// invoke method
await this._py
.ex`res_AffinityPropagation_get_metadata_routing = bridgeAffinityPropagation[${this.id}].get_metadata_routing(**pms_AffinityPropagation_get_metadata_routing)`
// convert the result from python to node.js
return this
._py`res_AffinityPropagation_get_metadata_routing.tolist() if hasattr(res_AffinityPropagation_get_metadata_routing, 'tolist') else res_AffinityPropagation_get_metadata_routing`
}
/**
Predict the closest cluster each sample in X belongs to.
*/
async predict(opts: {
/**
New data to predict. If a sparse matrix is provided, it will be converted into a sparse `csr\_matrix`.
*/
X?: ArrayLike | SparseMatrix[]
}): Promise<NDArray> {
if (this._isDisposed) {
throw new Error(
'This AffinityPropagation instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error('AffinityPropagation must call init() before predict()')
}
// set up method params
await this._py.ex`pms_AffinityPropagation_predict = {'X': np.array(${
opts['X'] ?? undefined
}) if ${opts['X'] !== undefined} else None}
pms_AffinityPropagation_predict = {k: v for k, v in pms_AffinityPropagation_predict.items() if v is not None}`
// invoke method
await this._py
.ex`res_AffinityPropagation_predict = bridgeAffinityPropagation[${this.id}].predict(**pms_AffinityPropagation_predict)`
// convert the result from python to node.js
return this
._py`res_AffinityPropagation_predict.tolist() if hasattr(res_AffinityPropagation_predict, 'tolist') else res_AffinityPropagation_predict`
}
/**
Indices of cluster centers.
*/
get cluster_centers_indices_(): Promise<NDArray> {
if (this._isDisposed) {
throw new Error(
'This AffinityPropagation instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error(
'AffinityPropagation must call init() before accessing cluster_centers_indices_'
)
}
return (async () => {
// invoke accessor
await this._py
.ex`attr_AffinityPropagation_cluster_centers_indices_ = bridgeAffinityPropagation[${this.id}].cluster_centers_indices_`
// convert the result from python to node.js
return this
._py`attr_AffinityPropagation_cluster_centers_indices_.tolist() if hasattr(attr_AffinityPropagation_cluster_centers_indices_, 'tolist') else attr_AffinityPropagation_cluster_centers_indices_`
})()
}
/**
Cluster centers (if affinity != `precomputed`).
*/
get cluster_centers_(): Promise<NDArray[]> {
if (this._isDisposed) {
throw new Error(
'This AffinityPropagation instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error(
'AffinityPropagation must call init() before accessing cluster_centers_'
)
}
return (async () => {
// invoke accessor
await this._py
.ex`attr_AffinityPropagation_cluster_centers_ = bridgeAffinityPropagation[${this.id}].cluster_centers_`
// convert the result from python to node.js
return this
._py`attr_AffinityPropagation_cluster_centers_.tolist() if hasattr(attr_AffinityPropagation_cluster_centers_, 'tolist') else attr_AffinityPropagation_cluster_centers_`
})()
}
/**
Labels of each point.
*/
get labels_(): Promise<NDArray> {
if (this._isDisposed) {
throw new Error(
'This AffinityPropagation instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error(
'AffinityPropagation must call init() before accessing labels_'
)
}
return (async () => {
// invoke accessor
await this._py
.ex`attr_AffinityPropagation_labels_ = bridgeAffinityPropagation[${this.id}].labels_`
// convert the result from python to node.js
return this
._py`attr_AffinityPropagation_labels_.tolist() if hasattr(attr_AffinityPropagation_labels_, 'tolist') else attr_AffinityPropagation_labels_`
})()
}
/**
Stores the affinity matrix used in `fit`.
*/
get affinity_matrix_(): Promise<NDArray[]> {
if (this._isDisposed) {
throw new Error(
'This AffinityPropagation instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error(
'AffinityPropagation must call init() before accessing affinity_matrix_'
)
}
return (async () => {
// invoke accessor
await this._py
.ex`attr_AffinityPropagation_affinity_matrix_ = bridgeAffinityPropagation[${this.id}].affinity_matrix_`
// convert the result from python to node.js
return this
._py`attr_AffinityPropagation_affinity_matrix_.tolist() if hasattr(attr_AffinityPropagation_affinity_matrix_, 'tolist') else attr_AffinityPropagation_affinity_matrix_`
})()
}
/**
Number of iterations taken to converge.
*/
get n_iter_(): Promise<number> {
if (this._isDisposed) {
throw new Error(
'This AffinityPropagation instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error(
'AffinityPropagation must call init() before accessing n_iter_'
)
}
return (async () => {
// invoke accessor
await this._py
.ex`attr_AffinityPropagation_n_iter_ = bridgeAffinityPropagation[${this.id}].n_iter_`
// convert the result from python to node.js
return this
._py`attr_AffinityPropagation_n_iter_.tolist() if hasattr(attr_AffinityPropagation_n_iter_, 'tolist') else attr_AffinityPropagation_n_iter_`
})()
}
/**
Number of features seen during [fit](../../glossary.html#term-fit).
*/
get n_features_in_(): Promise<number> {
if (this._isDisposed) {
throw new Error(
'This AffinityPropagation instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error(
'AffinityPropagation must call init() before accessing n_features_in_'
)
}
return (async () => {
// invoke accessor
await this._py
.ex`attr_AffinityPropagation_n_features_in_ = bridgeAffinityPropagation[${this.id}].n_features_in_`
// convert the result from python to node.js
return this
._py`attr_AffinityPropagation_n_features_in_.tolist() if hasattr(attr_AffinityPropagation_n_features_in_, 'tolist') else attr_AffinityPropagation_n_features_in_`
})()
}
/**
Names of features seen during [fit](../../glossary.html#term-fit). Defined only when `X` has feature names that are all strings.
*/
get feature_names_in_(): Promise<NDArray> {
if (this._isDisposed) {
throw new Error(
'This AffinityPropagation instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error(
'AffinityPropagation must call init() before accessing feature_names_in_'
)
}
return (async () => {
// invoke accessor
await this._py
.ex`attr_AffinityPropagation_feature_names_in_ = bridgeAffinityPropagation[${this.id}].feature_names_in_`
// convert the result from python to node.js
return this
._py`attr_AffinityPropagation_feature_names_in_.tolist() if hasattr(attr_AffinityPropagation_feature_names_in_, 'tolist') else attr_AffinityPropagation_feature_names_in_`
})()
}
}