Batched BIRCH: Set-Wise Clustering of Embedding Vectors with NumPy

2026-11-30来源 dev.toEnglish

Batched BIRCH is a NumPy-based implementation of incremental clustering that processes observations in waves instead of inserting them individually.

The implementation uses vectorized similarity scoring, deterministic candidate selection, joint clustering-feature updates, and optional parallel scoring.

  • Source: GitHub
  • Package: PyPI
  • License: Apache-2.0

1. Implementation

Traditional BIRCH inserts observations sequentially. Each insertion searches an existing CF-tree, updates clustering features, and may trigger structural changes.

Batched BIRCH evaluates an entire wave against a fixed snapshot of existing groups.

Processing consists of seven operations:

  1. Compute similarities between incoming vectors and group centroids.
  2. Select the top-k candidate groups for each vector.
  3. Evaluate similarity, dispersion, and capacity constraints.
  4. Select acceptable assignments using deterministic tie-breaking.
  5. Merge accepted observations into their destination groups jointly.
  6. Consolidate unassigned observations into new groups.
  7. Split groups exceeding capacity or dispersion limits.

Existing groups are not updated during candidate evaluation. Updates are applied after assignment decisions have been calculated.

The current implementation maintains flat clustering-feature groups. It does not implement hierarchical CF-tree routing.

2. Vectorized Candidate Evaluation

For a wave containing W vectors of dimension D, and G group centroids, scoring uses matrix multiplication:

scores = X @ C.T 

The output has shape W × G. Input vectors are unit-normalized for similarity scoring; the implementation applies its cosine-based candidate criterion.

Candidates are selected using argpartition, followed by deterministic ordering. Boundary ties are resolved by group index.

Candidate acceptance applies three constraints:

  • min_similarity — minimum similarity for joining a group.
  • max_dispersion — maximum permitted dispersion after insertion.
  • max_children — maximum group capacity.

Acceptable candidates are ranked by resulting dispersion, similarity, and group index.

With multiple workers, centroid rows are divided into blocks. Each worker calculates local scores and top-k candidates, which are merged into the global top-k without materializing the entire wave-by-group score matrix.

Tests cover candidate selection consistency across one, two, and four workers. Minor floating-point differences between BLAS kernels are possible.

3. Clustering-Feature Representation

The implementation stores numerically stable clustering features:

CF = (n, μ, S) n = number of observations μ = mean vector S = sum of squared deviations from the mean dispersion = S / n 

Statistics use Welford-style accumulation and Chan-style group merging, following established numerical methods also used in BETULA.

For two groups A and B:

n = nA + nB δ = μB - μA μ = μA + δ × (nB / n) S = SA + SB + ||δ||² × (nA × nB / n) 

This representation avoids cancellation errors from calculating dispersion by subtracting large raw sums of squares. It also supports joint updates: observations assigned to the same group can be aggregated independently and merged with the existing group's statistics.

4. Benchmarks

Controlled benchmarks were recorded on November 25, 2026.

Environment:

  • AMD EPYC 9D25, approximately 1.5 shared CPUs
  • Python 3.12.3
  • NumPy 2.5.5
  • scikit-learn 1.9.1
  • Single-threaded BLAS for the reported controlled arms
  • Imports and data loading excluded from fit timing

Synthetic Dataset: 100,000 Observations

100,000 synthetic observations, 384 dimensions, 50 generated blobs.

Implementation Fit time Groups
Batched BIRCH, wave 256 43.6 s 18,824
sklearn BIRCH, threshold 0.5 211.1 s 94,303

The implementations use different acceptance rules and produce substantially different partitions. This is not an equivalent-clustering speedup comparison.

WordNet Embeddings: 31,388 Observations

31,388 selected WordNet synsets represented using 384-dimensional MiniLM embeddings.

Implementation Fit time Groups Coherence
Batched BIRCH, wave 256 5.07 s 4,796 0.504
sklearn BIRCH, threshold 0.5 15.62 s 20,312 0.718
sklearn BIRCH, threshold 0.865 4.85 s 5,278 0.373

Coherence is the pair-weighted mean intra-cluster cosine similarity.

The final sklearn configuration approximates Batched BIRCH's group count but does not match its clustering semantics. At this granularity, sklearn was slightly faster.

The exact WordNet subset cannot be reconstructed solely from public source data. The repository documents a method-level regeneration procedure. The synthetic benchmarks are reproducible from the published scripts and seeds.

Parallel Scoring

Measurements on an eight-core AMD Ryzen 7 7735HS laptop, using 100,000 synthetic vectors:

Workers Runtime
1 45.9 s
2 35.1 s
4 31.5 s

All configurations produced 18,824 groups.

The one-worker measurement used an earlier code revision than the later worker measurements. These figures are preliminary scaling evidence, not a controlled same-revision speedup comparison.

Parallel scoring does not eliminate sequential consolidation and splitting costs.

5. Wave-Size Behavior

Wave size affects clustering results because observations within one wave are evaluated against a fixed group snapshot.

Measured group counts on the WordNet dataset:

Wave size Groups
1 4,497
32 4,689
256 4,796
1,024 4,965

wave_size=1 provides sequential insertion behavior within this implementation, but does not reproduce sklearn's hierarchical BIRCH algorithm.

For reproducibility, fix the input ordering, wave size, and configuration.

6. Limitations

Scoring Complexity

Candidate scoring costs O(W × G × D) per wave. The flat group structure requires scoring incoming observations against existing group centroids.

Without hierarchical routing, total processing cost may approach quadratic growth as the number of groups increases.

Memory

The implementation retains normalized float64 observation vectors for group splitting.

For one million observations with 384 dimensions, retained vector history requires approximately 3.07 GB, excluding additional allocations.

Partition Compatibility

Batched BIRCH is not a drop-in replacement for sklearn.cluster.Birch.

The implementations differ in group structure, similarity metric, acceptance rules, insertion semantics, and resulting partitions.

Semantic Correctness

Embedding similarity does not guarantee semantic equivalence.

The WordNet evaluation identified clusters combining unrelated senses of the same word. Applications requiring semantic correctness need additional validation.

7. Installation and Usage

Requires Python 3.10 or later and NumPy 1.24 or later.

pip install batched-birch 

Example:

import numpy as np from batched_birch import BirchConfig, BirchTree X = np.load("vectors.npy") config = BirchConfig( min_similarity=0.5, max_dispersion=0.5, max_children=16, candidate_count=5, workers=1, ) tree = BirchTree(config) tree.fit(X, wave_size=256) print(tree.n_groups) print(tree.labels_) 

Incremental processing is available through partial_fit(). Lower-level interfaces expose wave placement, clustering-feature tables, and group splitting.

8. Source and Reproducibility

Batched BIRCH 0.1.0 is published under the Apache-2.0 license.

The repository contains benchmark scripts, recorded measurements, tests, and implementation documentation.

原文:https://www.a8q9.cn/en/article/batched-birch-set-wise-clustering-of-embedding-vectors-with-numpy-722517.html

相关文章