Worked Example¶
This page walks through a complete vqlp workflow on synthetic data:
- Generate synthetic data (
sklearn.make_blobs) including true labels - Fit prototypes via FAISS k-means (
VQFitter) - Run full recall analysis on the learned prototypes (
VQRecaller), passing labels to compute WL / WL_Dist / WL_Purity - Plot the data and connectivity graph, coloring prototypes by their winning label (WL)
- Save the fitted model to disk and reload it
- Inspect all recall products including label summaries
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from sklearn.datasets import make_blobs
from vqlp import VQFitter
1. Generate synthetic data¶
We create six Gaussian blobs in 2D so the result is easy to plot. We ask for
more prototypes (M = 20) than there are blobs, which produces a richer
connectivity (CONN) structure across each blob.
make_blobs returns true_labels (integer blob IDs 0–5) alongside the data
matrix. We build a fixed per-label color map here so the same color is used
consistently across all panels.
N_SAMPLES = 500
N_BLOBS = 6
N_FEATURES = 2 # 2D so we can plot it easily
M_PROTOTYPES = 20 # more prototypes than blobs → richer CONN structure
X, true_labels = make_blobs(
n_samples=N_SAMPLES,
n_features=N_FEATURES,
centers=N_BLOBS,
cluster_std=0.8,
random_state=42
)
print(f"Data shape : {X.shape}")
print(f"Unique labels: {np.unique(true_labels)}")
# Fixed color map: label i → tab10 color i (consistent across all panels)
label_cmap = matplotlib.colormaps.get_cmap("tab10").resampled(N_BLOBS)
label_colors = {lbl: label_cmap(i) for i, lbl in enumerate(np.unique(true_labels))}
Data shape : (500, 2) Unique labels: [0 1 2 3 4 5]
2. Fit prototypes¶
With p=2 (Euclidean), VQFitter defaults to the FAISS k-means backend. We
run several restarts (nredo=3) and keep the best result. After fitting, the
prototype matrix is available as fitter.W with shape (M, d).
fitter = VQFitter(M=M_PROTOTYPES, p=2, max_bmu=2, random_state=42)
fitter.fit(X, method="kmeans", niter=30, nredo=3)
W = fitter.W # prototype matrix, shape (M, d)
print(f"Prototype matrix shape: {W.shape}")
Running FAISS k-means with 20 clusters (niter=30, nredo=3)... K-means complete. Final MQE: 0.507609 Fitting complete using kmeans method. Prototype matrix shape: (20, 2)
WARNING clustering 500 points to 20 centroids: please provide at least 780 training points
3. Full recall analysis¶
recall() finalises the recall products (receptive fields, connectivity, etc.)
on the training data. Passing labels=true_labels additionally triggers
recall_labels(), which computes:
WL– winning label per prototype (object array,Nonefor empty RFs)WL_Dist– row-normalized fuzzy label frequency table(M, n_labels)WL_Purity– Hellinger-based purity score per prototype(M,)WL_unq– sorted unique label values (column key forWL_Dist)
The underlying VQRecaller is exposed as fitter.recaller.
fitter.recall(labels=true_labels) # finalises RF, CONN, AFF, and label recall
recaller = fitter.recaller
Receptive fields computed. Connectivity matrix computed. Label recall complete. 20/20 prototypes labeled (6 unique labels). Mean purity: 0.9266 Recall analysis complete. MQE: 0.507609
4. Visualize assignments and connectivity¶
Left panel – data points colored by their true blob label; prototype markers colored by their winning label (WL), so you can immediately see which blob each prototype represents.
Right panel – the CONN graph with the same WL-based node colors; edge width scales with connectivity strength; node area scales with RF size.
fig, axes = plt.subplots(1, 2, figsize=(14, 6))
# --- Left panel: data colored by true label, prototypes by WL ---------------
ax = axes[0]
ax.set_title("Data colored by true label\nPrototypes colored by winning label (WL)")
for lbl in np.unique(true_labels):
mask = true_labels == lbl
ax.scatter(X[mask, 0], X[mask, 1],
color=label_colors[lbl], s=15, alpha=0.5, zorder=1,
label=f"Blob {lbl}")
# Prototype face color = WL color; grey if empty RF (WL is None)
proto_colors = [
label_colors[recaller.WL[i]] if recaller.WL[i] is not None else (0.7, 0.7, 0.7, 1.0)
for i in range(M_PROTOTYPES)
]
ax.scatter(W[:, 0], W[:, 1],
c=proto_colors, marker="X", s=160,
edgecolors="black", linewidths=0.8, zorder=3,
label="Prototypes (WL color)")
ax.legend(loc="upper right", fontsize=7, ncol=2)
ax.set_xlabel("Feature 1")
ax.set_ylabel("Feature 2")
# --- Right panel: CONN graph with WL-colored nodes --------------------------
ax = axes[1]
ax.set_title("CONN graph\n(edge width ∝ connectivity, node size ∝ RF size, node color = WL)")
conn_csr = recaller.CONN.tocsr()
for i in range(recaller._M):
for j in recaller.CONN_nhbs[i]:
if j <= i: # draw each edge once
continue
weight = conn_csr[i, j]
ax.plot([W[i, 0], W[j, 0]],
[W[i, 1], W[j, 1]],
color="steelblue", linewidth=weight * 0.3, alpha=0.6, zorder=1)
rf_sizes = recaller.RFSize
ax.scatter(W[:, 0], W[:, 1],
s=rf_sizes * 4 + 20,
c=proto_colors,
edgecolors="black", linewidths=0.5, zorder=2)
for i, (x, y) in enumerate(W):
ax.annotate(str(i), (x, y), fontsize=7, ha="center", va="center",
color="white", fontweight="bold", zorder=3)
ax.set_xlabel("Feature 1")
ax.set_ylabel("Feature 2")
plt.tight_layout()
plt.show()
5. Save and load¶
Once a VQFitter has been fitted and recalled, it is straightforward to
persist the entire object — including the embedded VQRecaller and all its
computed products — to an HDF5 file for later use.
fitter.save("fitter.h5")
fitter = VQFitter.load("fitter.h5")
The file stores hyperparameters, the prototype matrix W, and the full
recaller state (BMU assignments, receptive fields, connectivity matrices,
label recall products, etc.) in a structured HDF5 layout. Any attribute
that was None at save time (e.g. WL if recall_labels() was not
called) is restored as None on load.
In the cell below we save the fitted fitter, reload it into a fresh variable, and confirm that the prototype matrix and a selection of recall products are recovered exactly. The rest of this example then continues with the reloaded object, implicitly validating the round-trip.
SAVE_PATH = "vqlp_example.h5"
# Save the complete fitted fitter (prototype matrix + all recall products)
fitter.save(SAVE_PATH)
print(f"Saved to {SAVE_PATH}")
# Reload into a fresh variable in a new session this would be the entry point
fitter = VQFitter.load(SAVE_PATH)
recaller = fitter.recaller
W = fitter.W
print(f"Reloaded from {SAVE_PATH}")
# Spot-check: confirm key products survived the round-trip
import os
assert fitter.W.shape == (M_PROTOTYPES, N_FEATURES), "W shape mismatch"
assert recaller.BMU.shape[0] == N_SAMPLES, "BMU row count mismatch"
assert recaller.CONN is not None, "CONN missing after load"
assert list(recaller.WL_unq) == list(range(N_BLOBS)), "WL_unq mismatch"
print(f"Round-trip checks passed ✓")
print(f"File size: {os.path.getsize(SAVE_PATH) / 1024:.1f} KB")
Saved to vqlp_example.h5 Reloaded from vqlp_example.h5 Round-trip checks passed ✓ File size: 56.7 KB
6. Inspect the recall products¶
get_summary() returns aggregate statistics; when label recall has been run it
also reports n_unique_labels, labeled_prototypes, mean_label_purity, and
min_label_purity.
Below that we inspect the per-observation BMU / QE / AFF arrays, the receptive fields, the connectivity matrix, the label recall products, and finally hard vs. soft reconstruction error.
print("--- get_summary() ---")
summary = fitter.get_summary()
for k, v in summary.items():
print(f" {k:35s}: {v}")
--- get_summary() --- fitted : True M : 20 d : 2 p_norm : 2.0 max_bmu : 2 random_state : 42 N : 500 index_type : flat mean_quantization_error : 0.5076089868769049 empty_prototypes : 0 largest_rf_size : 53 connectivity_edges : 26 mean_connectivity_degree : 2.6 max_connectivity_degree : 4 n_unique_labels : 6 labeled_prototypes : 20 mean_label_purity : 0.9266014122834244 min_label_purity : 0.5567032853699805
print("--- BMU, QE & AFF (first 8 observations) ---")
print(f" BMU shape : {recaller.BMU.shape} (N x max_bmu)")
print(f" QE shape : {recaller.QE.shape} (N x max_bmu)")
print(f" AFF shape : {recaller.AFF.shape} (N x max_bmu)")
for i in range(8):
print(f" obs {i:3d} | 1st BMU: {recaller.BMU[i,0]:3d} QE1: {recaller.QE[i,0]:.4f}"
f" AFF1: {recaller.AFF[i,0]:.4f}"
f" | 2nd BMU: {recaller.BMU[i,1]:3d} QE2: {recaller.QE[i,1]:.4f}"
f" AFF2: {recaller.AFF[i,1]:.4f}")
--- BMU, QE & AFF (first 8 observations) --- BMU shape : (500, 2) (N x max_bmu) QE shape : (500, 2) (N x max_bmu) AFF shape : (500, 2) (N x max_bmu) obs 0 | 1st BMU: 16 QE1: 0.2925 AFF1: 0.8164 | 2nd BMU: 10 QE2: 1.0077 AFF2: 0.1836 obs 1 | 1st BMU: 9 QE1: 0.2430 AFF1: 0.9436 | 2nd BMU: 15 QE2: 3.8245 AFF2: 0.0564 obs 2 | 1st BMU: 9 QE1: 1.0912 AFF1: 0.8273 | 2nd BMU: 15 QE2: 4.1360 AFF2: 0.1727 obs 3 | 1st BMU: 10 QE1: 3.7886 AFF1: 0.7258 | 2nd BMU: 8 QE2: 6.2403 AFF2: 0.2742 obs 4 | 1st BMU: 14 QE1: 0.2723 AFF1: 0.9390 | 2nd BMU: 1 QE2: 3.9224 AFF2: 0.0610 obs 5 | 1st BMU: 10 QE1: 0.1096 AFF1: 0.9229 | 2nd BMU: 2 QE2: 1.2015 AFF2: 0.0771 obs 6 | 1st BMU: 1 QE1: 0.5480 AFF1: 0.8627 | 2nd BMU: 15 QE2: 2.8941 AFF2: 0.1373 obs 7 | 1st BMU: 9 QE1: 1.7255 AFF1: 0.8404 | 2nd BMU: 15 QE2: 7.3617 AFF2: 0.1596
print("--- Receptive fields (RF) ---")
print(f" RFSize range: {recaller.RFSize.min()} - {recaller.RFSize.max()} observations")
print(f" Empty prototypes: {int(np.sum(recaller.RFSize == 0))}")
for i in range(min(5, M_PROTOTYPES)):
print(f" RF[{i}]: {recaller.RFSize[i]:3d} obs -> indices {recaller.RF[i][:6]}{'...' if recaller.RFSize[i] > 6 else ''}")
--- Receptive fields (RF) --- RFSize range: 2 - 53 observations Empty prototypes: 0 RF[0]: 10 obs -> indices [41, 115, 150, 168, 190, 196]... RF[1]: 43 obs -> indices [6, 25, 43, 49, 50, 57]... RF[2]: 30 obs -> indices [10, 16, 53, 70, 71, 96]... RF[3]: 27 obs -> indices [18, 19, 97, 114, 128, 134]... RF[4]: 25 obs -> indices [26, 31, 42, 176, 177, 181]...
print("--- Connectivity matrix (CONN) ---")
print(f" CONN shape : {recaller.CONN.shape} (M x M, sparse)")
print(f" Nonzero entries: {recaller.CONN.nnz} ({summary['connectivity_edges']} unique edges)")
print(f" Degree range: {recaller.CONN_nhbs_size.min()} - {recaller.CONN_nhbs_size.max()} neighbors")
print(f" Mean degree : {summary['mean_connectivity_degree']:.2f}")
for i in range(min(5, M_PROTOTYPES)):
print(f" Prototype {i:2d}: {recaller.CONN_nhbs_size[i]} neighbors -> {recaller.CONN_nhbs[i]}")
--- Connectivity matrix (CONN) --- CONN shape : (20, 20) (M x M, sparse) Nonzero entries: 52 (26 unique edges) Degree range: 1 - 4 neighbors Mean degree : 2.60 Prototype 0: 4 neighbors -> [2, 8, 10, 11] Prototype 1: 2 neighbors -> [14, 15] Prototype 2: 3 neighbors -> [0, 10, 16] Prototype 3: 2 neighbors -> [7, 12] Prototype 4: 4 neighbors -> [5, 6, 13, 19]
print("--- Label recall (WL / WL_Dist / WL_Purity) ---")
print(f" Unique labels seen : {recaller.WL_unq}")
print(f" WL shape : {recaller.WL.shape} (winning label per prototype)")
print(f" WL_Dist shape : {recaller.WL_Dist.shape} (M x n_unique_labels, row-normalized)")
print(f" WL_Purity shape : {recaller.WL_Purity.shape}")
print()
print(f" {'Proto':>6} {'WL':>5} {'Purity':>7} {'RF size':>7} WL_Dist (per label)")
print(f" {'-----':>6} {'--':>5} {'------':>7} {'-------':>7} "
+ " ".join(f"L{l}" for l in recaller.WL_unq))
for i in range(M_PROTOTYPES):
wl_str = str(recaller.WL[i]) if recaller.WL[i] is not None else 'None'
dist_str = " ".join(f"{recaller.WL_Dist[i, j]:.3f}" for j in range(len(recaller.WL_unq)))
print(f" {i:6d} {wl_str:>5} {recaller.WL_Purity[i]:7.4f} {recaller.RFSize[i]:7d} {dist_str}")
--- Label recall (WL / WL_Dist / WL_Purity) ---
Unique labels seen : [0 1 2 3 4 5]
WL shape : (20,) (winning label per prototype)
WL_Dist shape : (20, 6) (M x n_unique_labels, row-normalized)
WL_Purity shape : (20,)
Proto WL Purity RF size WL_Dist (per label)
----- -- ------ ------- L0 L1 L2 L3 L4 L5
0 4 0.6281 10 0.000 0.257 0.000 0.000 0.743 0.000
1 3 0.9046 43 0.000 0.000 0.000 0.982 0.000 0.018
2 1 0.9769 30 0.000 0.999 0.000 0.000 0.001 0.000
3 2 1.0000 27 0.000 0.000 1.000 0.000 0.000 0.000
4 0 1.0000 25 1.000 0.000 0.000 0.000 0.000 0.000
5 0 1.0000 13 1.000 0.000 0.000 0.000 0.000 0.000
6 0 1.0000 11 1.000 0.000 0.000 0.000 0.000 0.000
7 2 1.0000 28 0.000 0.000 1.000 0.000 0.000 0.000
8 4 0.9279 44 0.000 0.010 0.000 0.000 0.990 0.000
9 5 0.9249 53 0.000 0.000 0.000 0.011 0.000 0.989
10 1 0.8716 25 0.000 0.967 0.000 0.000 0.033 0.000
11 4 1.0000 32 0.000 0.000 0.000 0.000 1.000 0.000
12 2 1.0000 26 0.000 0.000 1.000 0.000 0.000 0.000
13 0 1.0000 13 1.000 0.000 0.000 0.000 0.000 0.000
14 3 0.7414 27 0.000 0.000 0.000 0.871 0.000 0.129
15 5 0.5567 43 0.000 0.000 0.000 0.354 0.000 0.646
16 1 1.0000 26 0.000 1.000 0.000 0.000 0.000 0.000
17 2 1.0000 2 0.000 0.000 1.000 0.000 0.000 0.000
18 0 1.0000 8 1.000 0.000 0.000 0.000 0.000 0.000
19 0 1.0000 14 1.000 0.000 0.000 0.000 0.000 0.000
print("--- Reconstruction ---")
X_hard = recaller.reconstruct(W, X, method="hard")
X_soft = recaller.reconstruct(W, X, method="soft")
hard_err = np.mean(np.linalg.norm(X - X_hard, axis=1))
soft_err = np.mean(np.linalg.norm(X - X_soft, axis=1))
print(f" Hard reconstruction mean L2 error: {hard_err:.4f}")
print(f" Soft reconstruction mean L2 error: {soft_err:.4f}")
--- Reconstruction --- Soft reconstruction complete. Hard reconstruction mean L2 error: 0.6287 Soft reconstruction mean L2 error: 0.6148