BBKNN (Batch-balanced KNN) is a graph-based batch correction algorithm that constructs a k-nearest neighbor graph where each cell's neighborhood is assembled by independently identifying the k nearest neighbors within each batch, then concatenating these batch-specific neighbor sets. This batch-balanced connectivity ensures that a cell's local neighborhood contains representatives from every batch, effectively removing batch-specific structure from the graph topology without altering the original gene expression matrix.
Glossary
BBKNN (Batch-balanced KNN)

What is BBKNN (Batch-balanced KNN)?
BBKNN is a graph-based data integration algorithm that constructs a k-nearest neighbor graph where each cell is connected to neighbors from each batch independently, effectively removing batch structure from the neighborhood graph without modifying the underlying expression data.
Unlike embedding-based methods such as Harmony or MNN, BBKNN operates directly on the neighborhood graph and does not produce a corrected expression matrix, making it a lightweight preprocessing step for downstream tasks like clustering and visualization. The algorithm is particularly effective for single-cell RNA sequencing and spatial transcriptomics data, where it prevents batch-driven segregation in UMAP or t-SNE visualizations while preserving genuine biological variation.
Key Features of BBKNN
BBKNN is a graph-based data integration algorithm that constructs a k-nearest neighbor graph where each cell is connected to neighbors from each batch independently, effectively removing batch structure from the neighborhood graph.
Batch-Balanced Neighbor Selection
Unlike standard KNN which can be dominated by cells from the largest batch, BBKNN constructs the neighborhood graph by independently identifying the k-nearest neighbors within each batch for every cell. This ensures that each cell's local neighborhood contains equal representation from all batches, effectively neutralizing batch-specific biases. The algorithm then merges these per-batch neighbor lists into a single, batch-balanced adjacency matrix, creating a graph where biological variation is preserved but technical batch structure is eliminated.
Graph-Based Integration Without Embedding Correction
BBKNN operates exclusively on the neighborhood graph topology rather than modifying the underlying gene expression matrix. This is a fundamental distinction from methods like ComBat or Harmony:
- No corrected expression values are produced
- The original count matrix remains untouched
- Only the connectivity structure is adjusted This makes BBKNN ideal as a preprocessing step for graph-based downstream analyses such as Leiden clustering, UMAP visualization, and PAGA trajectory inference, where only the neighbor relations matter.
Trimodal Connectivity for Rare Cell Types
BBKNN introduces a trimodal weighting scheme for neighbor connections that enhances sensitivity to rare populations. The algorithm computes three distinct connectivity measures:
- Raw neighbor count: The number of times a cell pair appears as mutual neighbors
- Batch-balanced weighting: Adjusts for batch size disparities
- Fuzzy simplicial set: A topological representation that preserves local structure This trimodal approach ensures that rare cell types (as low as 0.1% frequency) maintain robust connectivity even when they are unevenly distributed across batches, preventing their absorption into dominant populations during graph construction.
Scalable Approximate Nearest Neighbors
BBKNN leverages approximate nearest neighbor (ANN) algorithms via the umap-learn library to achieve sub-quadratic runtime complexity. For datasets exceeding 100,000 cells, exact KNN computation becomes computationally prohibitive. BBKNN's ANN implementation:
- Uses random projection trees for initial space partitioning
- Employs neighborhood graph search for refinement
- Scales to millions of cells on standard compute hardware
- Maintains >95% recall of true nearest neighbors This scalability makes BBKNN suitable for large-scale atlas integration projects like the Human Cell Atlas.
Integration with Scanpy Ecosystem
BBKNN is natively integrated into the Scanpy single-cell analysis toolkit, providing a seamless workflow:
bbknn.bbknn()replacessc.pp.neighbors()in standard pipelines- Outputs a standard AnnData object with
.obsp['connectivities']and.obsp['distances'] - Compatible with all downstream Scanpy functions:
sc.tl.leiden(),sc.tl.umap(),sc.tl.paga() - Supports batch-aware highly variable gene selection via
bbknn.pca_matrix()This tight integration allows bioinformaticians to incorporate batch correction without restructuring existing analysis pipelines.
Connectivity-Based Batch Mixing Metrics
BBKNN provides quantitative evaluation of integration quality through graph-based mixing metrics:
- kBET acceptance rate: Measures local batch label distribution against global expectation; values near 1.0 indicate perfect mixing
- Graph connectivity: Assesses whether the integrated graph fragments into batch-isolated subgraphs
- Neighbor purity: Quantifies the proportion of same-batch neighbors before and after correction These metrics enable objective comparison against alternative methods like Harmony, Scanorama, and Seurat v3, allowing researchers to select the optimal integration strategy for their specific dataset characteristics.
BBKNN vs. Other Batch Correction Methods
A feature-level comparison of BBKNN against Harmony, MNN, and ComBat for single-cell data integration tasks.
| Feature | BBKNN | Harmony | MNN | ComBat |
|---|---|---|---|---|
Core Algorithm | Graph-based k-NN with per-batch neighbors | Iterative soft clustering in shared embedding | Mutual nearest neighbor pair identification | Empirical Bayes location/scale adjustment |
Output Type | Connectivity graph (uncorrected expression) | Corrected embedding matrix | Corrected expression matrix | Corrected expression matrix |
Preserves Raw Counts | ||||
Handles >2 Batches Natively | ||||
Scalability (100k+ cells) | ||||
Requires Shared Cell Types Across Batches | ||||
Integration Metric | kBET acceptance rate | LISI diversity score | MNN pair count | Variance explained by batch |
Risk of Overcorrection | Low (graph only) | Moderate | Moderate | High (global adjustment) |
Frequently Asked Questions
Clear, technical answers to the most common questions about Batch-balanced KNN, a graph-based algorithm for integrating single-cell datasets across multiple experimental batches.
BBKNN (Batch-balanced K-nearest Neighbors) is a graph-based data integration algorithm that constructs a neighborhood graph where each cell is connected to a defined number of its nearest neighbors from each batch independently, rather than globally. The core mechanism involves building a separate k-nearest neighbor index for each batch using principal component analysis (PCA) space, then for every cell, querying each batch-specific index to find the k closest cells within that batch. These per-batch neighbor lists are concatenated to form the final adjacency matrix. This process effectively removes batch-specific structure from the neighborhood graph, as cells are forced to connect across batches, preventing the formation of isolated batch clusters. The resulting graph can be used directly for clustering with Leiden or Louvain community detection, or for visualization with UMAP or t-SNE, without requiring a corrected expression matrix. Unlike methods that output a batch-corrected feature matrix, BBKNN operates solely on the connectivity graph, making it computationally lightweight and scalable to millions of cells.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Explore the foundational algorithms, evaluation metrics, and complementary methods that contextualize BBKNN within the single-cell data integration ecosystem.
k-nearest Neighbor Graph (k-NN Graph)
The fundamental data structure upon which BBKNN operates. A k-NN graph connects each data point (cell) to its k most similar neighbors based on a distance metric, typically Euclidean distance in a high-dimensional expression space. Unlike traditional k-NN, BBKNN constructs this graph in a batch-balanced manner, ensuring each cell's neighborhood contains connections to a specified number of cells from every other batch, thereby forcing the mixing of technical replicates.
Mutual Nearest Neighbors (MNN)
A foundational batch correction concept that identifies pairs of cells from different batches that are mutual nearest neighbors in a shared expression space. These MNN pairs are assumed to represent the same biological cell type and are used to estimate a correction vector. BBKNN can be seen as a graph-based generalization of this principle, where the batch-balanced k-NN graph implicitly identifies cross-batch neighbors without requiring strict mutuality, making it more robust to population imbalances.
kBET (k-nearest neighbor Batch Effect Test)
A quantitative metric designed to evaluate the degree of batch mixing in a neighborhood graph. kBET performs a chi-squared test on the local batch label distribution within a cell's k-nearest neighborhood and compares it to the global distribution. A well-mixed dataset yields an acceptance rate near 1.0. Since BBKNN directly optimizes for local batch balance, it is expected to score highly on this metric, making kBET a natural validation tool for BBKNN-integrated data.
Local Inverse Simpson's Index (LISI)
A diversity score computed for each cell's local neighborhood that quantifies the effective number of different batches (iLISI) or cell types (cLISI). For successful integration, a high iLISI (indicating many batches are mixed) and a high cLISI (indicating distinct cell types remain separate) are desired. BBKNN directly maximizes iLISI by construction, as it forces each cell to connect to a fixed number of neighbors from each batch.
Scanorama
An alternative integration algorithm that also leverages the concept of nearest neighbors. Scanorama identifies mutual nearest neighbors across all pairs of datasets and stitches them together into a unified panorama. While both methods are graph-based, BBKNN operates on the full dataset simultaneously and outputs a connectivity graph for downstream use (e.g., UMAP, clustering), whereas Scanorama produces a corrected expression matrix by merging overlapping panoramas.
Overcorrection Assessment
The critical process of evaluating whether a batch correction method like BBKNN has removed true biological variation alongside technical noise. A key risk is that forcing batch mixing can blend distinct, batch-specific cell types into an artificial intermediate state. Assessment involves verifying the preservation of known cell-type clusters and ensuring that biological covariates still explain significant variance in the integrated representation.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us