API Reference
The public API consists of two classes: VQFitter, which fits
prototypes, and VQRecaller, which computes recall products.
VQFitter
vqlp.VQFitter
VQFitter(
M, p=2, max_bmu=2, random_state=None, verbose=True
)
Vector Quantizer Fitter using arbitrary Lp distance metrics.
Supports multiple fitting algorithms including random sampling, IRLS (Iteratively Reweighted Least Squares), gradient descent (GD), PAM (Partitioning Around Medoids), and FAISS k-means (p=2 only).
Typical workflow
-
Instantiate with the desired number of prototypes M and Lp order p::
fitter = VQFitter(M=20, p=2, random_state=42)
-
Fit prototypes to a data matrix X of shape (N, d)::
fitter.fit(X) # defaults to k-means for p=2, IRLS otherwise
-
Run recall analysis to compute BMU assignments, receptive fields, connectivity, etc. Call with no arguments to analyze the training data, or pass new X to analyze held-out data::
fitter.recall() # training data fitter.recall(X_test) # new data
-
Inspect results via the embedded VQRecaller object::
recaller = fitter.recaller print(recaller.BMU) # shape (N, max_bmu) print(recaller.QE) # quantization errors print(recaller.RFSize) # receptive field sizes print(recaller.CONN) # sparse connectivity matrix
-
Optionally reconstruct data::
X_hard = recaller.reconstruct(fitter.W, X, method='hard') X_soft = recaller.reconstruct(fitter.W, X, method='soft')
See VQRecaller for definitions of BMU, QE, RF, CADJ, and CONN.
Initialize the VQ Fitter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
M
|
int
|
Number of prototypes to create |
required |
p
|
float
|
Order of the Lp distance metric (e.g., 1 for Manhattan, 2 for Euclidean) |
2
|
max_bmu
|
int
|
Number of Best Matching Units (closest prototypes) to track |
2
|
random_state
|
int or None
|
Seed for the instance-local random number generator. Reproducible results are guaranteed without touching the global NumPy random state, so multiple VQFitter instances with different seeds can coexist safely. |
None
|
verbose
|
bool
|
If True, print progress messages during fitting and recall. Set to False to suppress all terminal output. |
True
|
Source code in src/vqlp/vq.py
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 | |
fit
fit(X, method=None, distX=None, **kwargs)
Fit the vector quantizer using the specified method.
Defaults to "kmeans" when p=2, and "IRLS" otherwise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
(array - like, shape(N, d))
|
Training data matrix |
required |
method
|
str
|
Fitting method. One of: ["random", "IRLS", "GD", "PAM", "kmeans"]. Defaults to "kmeans" if p=2, "IRLS" otherwise. |
None
|
distX
|
(array, shape(N, N))
|
Precomputed distance matrix. If provided, internal distance calculation is skipped (PAM only). |
None
|
**kwargs
|
additional arguments
|
Method-specific parameters (see individual fit* methods). |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
self |
VQFitter
|
Returns self for method chaining |
Source code in src/vqlp/vq.py
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 | |
set_prototypes
set_prototypes(W, X)
Set the prototype matrix W directly, bypassing fitting.
Useful when prototypes are known in advance (e.g. from a previous run, an external algorithm, or domain-specific initialization) and you want to use the VQFitter machinery for recall analysis or as a warm start for further fitting.
BMU and QE are computed immediately from X, keeping the object in a consistent state — the same guarantee provided by all fit* methods.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
W
|
(array - like, shape(M, d))
|
Prototype matrix. Must have exactly self.M rows. If the data dimensionality d is already known (from a prior fit or recall), W must match it; otherwise d is inferred from W. |
required |
X
|
(array - like, shape(N, d))
|
Data matrix used to compute BMU and QE. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
self |
VQFitter
|
Returns self for method chaining |
Source code in src/vqlp/vq.py
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 | |
recall
recall(X=None, labels=None)
Perform recall analysis using the fitted prototypes.
This is a convenience wrapper around VQRecaller.recall(). The key difference from calling self.recaller.recall() directly is that W is always taken from self.W (the fitted prototypes), so you never need to pass it explicitly here.
If X is provided, performs recall analysis on new (e.g. held-out) data. If X is None, finalizes recall analysis on the training data (BMU was already updated incrementally during fitting).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
(array - like, shape(N, d))
|
Data matrix for recall analysis. If None, finalizes training recall. |
None
|
labels
|
(array - like, shape(N))
|
Observation labels. Any hashable type is accepted (int, str, float, etc.). If provided, recall_labels() is called automatically after the main recall pipeline to compute WL, WL_Dist, and WL_Purity. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
self |
VQFitter
|
Returns self for method chaining. |
See Also
VQRecaller.recall : The underlying recall method, which also accepts explicit W and p arguments for use outside of VQFitter.
Source code in src/vqlp/vq.py
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 | |
save
save(path)
Save the VQFitter (and its embedded VQRecaller) to an HDF5 file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Destination file path. Created or overwritten. |
required |
See Also
VQFitter.load : Reconstruct a VQFitter from a saved file. VQRecaller.save : Save a standalone VQRecaller.
Examples:
>>> fitter.save("fitter.h5")
>>> fitter2 = VQFitter.load("fitter.h5")
Source code in src/vqlp/vq.py
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 | |
load
classmethod
load(path)
Load a VQFitter (and its embedded VQRecaller) from an HDF5 file
created by :meth:save.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the HDF5 file. |
required |
Returns:
| Type | Description |
|---|---|
VQFitter
|
|
Examples:
>>> fitter = VQFitter.load("fitter.h5")
>>> fitter.W # prototype matrix
>>> fitter.recaller.BMU # recall products, if recall() was called before saving
Source code in src/vqlp/vq.py
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 | |
to_dict
to_dict()
Return a plain dict representation of this VQFitter.
Only hyperparameters and the prototype matrix W are included.
The embedded recaller is serialized separately by VQFitterIO.
The RNG (_rng) is not stored; on load it is re-initialized
from random_state.
Returns:
| Type | Description |
|---|---|
dict with keys: M, p, max_bmu, verbose, random_state, W
|
|
Source code in src/vqlp/vq.py
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 | |
from_dict
classmethod
from_dict(d)
Reconstruct a VQFitter from a dict produced by :meth:to_dict.
Bypasses __init__ so that hyperparameters are restored directly.
The RNG is re-initialized from random_state.
Note: recaller is set to None by this method.
:meth:VQFitterIO.load attaches the reconstructed VQRecaller after
calling from_dict. If you call from_dict directly, you are
responsible for setting obj.recaller before calling any method
that depends on it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict
|
As returned by :meth: |
required |
Returns:
| Type | Description |
|---|---|
VQFitter
|
|
Source code in src/vqlp/vq.py
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 | |
get_summary
get_summary()
Get a summary of the fitted model and recall analysis.
Returns:
| Type | Description |
|---|---|
dict
|
Summary statistics. Keys always present:
- If recall() has been called, all keys from VQRecaller.get_summary() are also included (MQE, RF sizes, connectivity stats, etc.). |
Source code in src/vqlp/vq.py
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 | |
VQRecaller
vqlp.VQRecaller
VQRecaller(
p=2,
max_bmu=2,
index_type="flat",
nlist=None,
nprobe=None,
verbose=True,
)
Recall analysis for Vector Quantizer results.
Computes and stores analysis products from applying a set of prototypes to data, including Best Matching Units, connectivity matrices, receptive fields, and reconstruction capabilities.
Nearest-prototype search is performed via FAISS, which supports arbitrary Lp metrics. Both exact (flat) and approximate (IVF) search are available via the index_type parameter.
Note: FAISS operates in float32 internally. Input data is cast to float32 for the search step regardless of input dtype.
Terminology
Prototype (W[m]) : One of M representative vectors in feature space,
also called a codebook vector or neuron. Shape (d,).
BMU (Best Matching Unit) : The prototype closest to a given observation
under the chosen Lp metric. A 2nd BMU, 3rd BMU, etc. are the next
closest prototypes. Controlled by max_bmu.
QE (Quantization Error) : The Lp distance from an observation to its
assigned BMU. Lower is better; zero means the observation sits
exactly on a prototype.
RF (Receptive Field) : The set of observations for which a given
prototype is the 1st BMU. Analogous to a Voronoi cell.
RFSize : The number of observations in each prototype's receptive field.
A prototype with RFSize == 0 is "dead" (no data point maps to it).
CADJ (Co-Adjacency matrix) : An M×M integer matrix where CADJ[i, j]
counts the number of observations whose 1st BMU is prototype i and
whose 2nd BMU is prototype j. Asymmetric by construction. Encodes
the directed manifold neighborhood of the codebook.
CONN (Connectivity matrix) : The symmetric version of CADJ:
CONN = CADJ + CADJ^T. Used for undirected neighborhood queries.
CONN[i, j] > 0 means prototypes i and j are topological neighbors.
Initialize VQRecaller.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p
|
float
|
Order of the Lp distance metric. Any positive value is supported for exact search (index_type="flat"). Approximate search (index_type="ivf") is restricted to p in {1, 2}. |
2
|
max_bmu
|
int
|
Number of Best Matching Units to track for each observation |
2
|
index_type
|
str
|
FAISS index type for nearest-neighbor search: - "flat": Exact brute-force search via IndexFlat. Correct for any p and recommended for codebooks up to a few thousand prototypes, and for any iterative fitting loop. - "ivf": Approximate search via IndexIVFFlat. Useful for very large codebooks where exact search is a bottleneck. Not suitable for iterative fitting (non-deterministic assignments interfere with convergence) and restricted to p in {1, 2}. |
"flat"
|
nlist
|
int
|
(IVF only) Number of Voronoi cells. Defaults to sqrt(M). |
None
|
nprobe
|
int
|
(IVF only) Number of cells searched at query time. Higher values give better recall at the cost of speed. Defaults to nlist // 10. |
None
|
verbose
|
bool
|
If True, print progress messages during recall analysis. Set to False to suppress all terminal output. |
True
|
Source code in src/vqlp/vq.py
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 | |
recall
recall(X=None, W=None, p=None, max_bmu=None, labels=None)
Perform recall analysis. Can operate in two modes:
Mode 1 - Full analysis: Provide X and W to compute everything from scratch Mode 2 - Finalize: Provide no arguments to compute derived quantities from existing BMU/QE (assumes update_BMU() was called)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
(array - like, shape(N, d))
|
Data matrix with N observations and d features |
None
|
W
|
(array - like, shape(M, d), optional)
|
Prototype matrix with M prototypes and d features |
None
|
p
|
float
|
Lp distance order. If None, uses self.p |
None
|
max_bmu
|
int
|
Number of BMUs to track. If None, uses self.max_bmu |
None
|
labels
|
(array - like, shape(N))
|
Observation labels. Any hashable type is accepted (int, str, float, etc.). If provided, recall_labels() is called automatically after the main recall pipeline. Can also be called independently via recall_labels() on an already-recalled object. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
self |
VQRecaller
|
Returns self for method chaining |
Source code in src/vqlp/vq.py
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 | |
update_BMU
update_BMU(X, W)
Update Best Matching Units (BMU) and Quantization Errors (QE) via FAISS.
This is the computationally expensive part of recall analysis. Can be called repeatedly during iterative fitting algorithms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
(array - like, shape(N, d))
|
Data matrix with N observations and d features |
required |
W
|
(array - like, shape(M, d))
|
Prototype matrix with M prototypes and d features |
required |
Source code in src/vqlp/vq.py
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 | |
recall_labels
recall_labels(labels)
Compute per-prototype label summaries from observation labels.
Must be called after update_BMU() (or recall()) so that self.BMU, self.AFF, self.RF, and self.RFSize are available.
For each observation i, its label receives fractional credit distributed across all max_bmu prototypes in proportion to their affinity weights (self.AFF[i, :]). This produces a fuzzy frequency table (WL_Dist) whose rows are then normalized to probability distributions. The winning label per prototype is the argmax of that distribution, and purity is derived from the Hellinger distance between the distribution and the ideal one-hot encoding of the winner.
This mirrors VQRecallLabels_worker / cpp_RecallLabels() from AnnoyVQRecall.hpp.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
(array - like, shape(N))
|
Observation labels. Any hashable type is accepted (int, str, float, etc.). Length must equal the number of observations used in the most recent update_BMU() / recall() call. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
self |
VQRecaller
|
Returns self for method chaining. |
Attributes set
WL : np.ndarray of object, shape (M,) Winning label for each prototype. None for prototypes whose receptive field is empty (RFSize == 0). WL_Dist : np.ndarray of float, shape (M, n_unique_labels) Row-normalized fuzzy label frequency table. Column j corresponds to WL_unq[j]. Rows for empty RFs are all-zero. WL_Purity : np.ndarray of float, shape (M,) Hellinger-based purity score in [0, 1]. 1 means all affinity mass falls on a single label; 0 for empty RFs. WL_unq : np.ndarray, shape (n_unique_labels,) Sorted unique label values. Use to interpret WL_Dist columns.
Source code in src/vqlp/vq.py
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 | |
reconstruct
reconstruct(W, X, method='hard')
Reconstruct data using the quantizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
W
|
(array - like, shape(M, d))
|
Prototype matrix with M prototypes and d features |
required |
X
|
(array - like, shape(N, d))
|
Data matrix to reconstruct with N observations and d features |
required |
method
|
str
|
Reconstruction method: - "hard": Use closest prototype for each observation (respects self.p) - "soft": Weighted average using UMAP-style local connectivity. Always uses Euclidean (L2) distances internally; see _reconstruct_soft for rationale. |
"hard"
|
Returns:
| Type | Description |
|---|---|
np.ndarray : Reconstructed data with shape (N, d)
|
|
Source code in src/vqlp/vq.py
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 | |
save
save(path)
Save the VQRecaller to an HDF5 file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Destination file path. Created or overwritten. |
required |
See Also
VQRecaller.load : Reconstruct a VQRecaller from a saved file.
Examples:
>>> recaller.save("recaller.h5")
>>> recaller2 = VQRecaller.load("recaller.h5")
Source code in src/vqlp/vq.py
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 | |
load
classmethod
load(path)
Load a VQRecaller from an HDF5 file created by :meth:save.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the HDF5 file. |
required |
Returns:
| Type | Description |
|---|---|
VQRecaller
|
|
Examples:
>>> recaller = VQRecaller.load("recaller.h5")
Source code in src/vqlp/vq.py
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 | |
get_summary
get_summary()
Get a summary of the recall analysis results.
Returns:
| Type | Description |
|---|---|
dict
|
Summary statistics with the following keys: Always present after recall():
- Present only after recall_labels():
- |
Source code in src/vqlp/vq.py
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 | |
to_dict
to_dict()
Return a plain dict representation of this VQRecaller.
All values are Python/numpy primitives (arrays, sparse matrices, ragged lists, scalars, or None) — no HDF5 types. Intended for use with VQRecallerIO, which handles HDF5 encoding via _write_dict.
Returns:
| Type | Description |
|---|---|
dict
|
|
Source code in src/vqlp/vq.py
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 | |
from_dict
classmethod
from_dict(d)
Reconstruct a VQRecaller from a dict produced by :meth:to_dict.
Bypasses __init__ so that all saved attributes are restored
directly without re-running any computation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict
|
As returned by :meth: |
required |
Returns:
| Type | Description |
|---|---|
VQRecaller
|
|
Source code in src/vqlp/vq.py
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 | |