Overview
Tree gating can identify high-confidence reference cells while leaving ambiguous cells unassigned. This vignette uses the stored core_group labels to train a weighted k-nearest-neighbour classifier and predict the remaining cells.
The example uses one complete image and reduced cross-validation settings to remain suitable for package checks.
library(cytoGateR)
data("cytoGateR_example", package = "cytoGateR")
image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name
spe <- cytoGateR_example[, image_ids == image_ids[1L]]
table(SummarizedExperiment::colData(spe)$core_group)
Bcell BnTcell CD4 CD8 Myeloid Neutrophil
236 337 227 206 108 12
Plasma_cell Stroma Treg Tumor Unassigned
40 71 125 16 2985
Train a weighted kNN reference
Only cells with a known core_group label are used during reference cleaning. The "Unassigned" cells are retained for subsequent prediction.
set.seed(1)
knn_reference <- train_custom_knn(
spe,
label_col = "core_group",
assay_name = "exprs",
unknown_label = "Unassigned",
features = c("CD3e", "CD20", "CD4", "CD8a"),
cv_folds = 2,
repeats = 1,
agreement_thresh = 0.5,
k = 3,
method = "pearson",
BPPARAM = BiocParallel::SerialParam()
)
The returned object contains a cleaned reference and cross-validated probabilities for retained reference cells:
[1] "spe" "model" "core_prob_mat" "agreement_rates"
[5] "features_used"
dim(knn_reference$model$reference_data)
table(knn_reference$model$reference_labels)
Bcell BnTcell CD4 CD8 Myeloid Neutrophil
180 197 160 166 44 0
Plasma_cell Stroma Treg Tumor
2 9 35 0
Predict unassigned cells
knn_prediction <- predict_unknown_with_knn(
knn_reference$spe,
knn_reference,
assay_name = "exprs",
label_col = "cleaned_core_label",
out_col = "knn_label_filled",
pred_col = "knn_pred",
unknown_label = "Unassigned",
threshold = 0.5,
k = 3,
dist_method = "pearson"
)
prediction_cd <- SummarizedExperiment::colData(knn_prediction$spe)
table(prediction_cd$knn_label_filled)
Bcell BnTcell CD4 CD8 Myeloid Plasma_cell
654 1390 829 520 589 2
Stroma Treg Unassigned
84 162 133
summary(prediction_cd$knn_confidence)
Min. 1st Qu. Median Mean 3rd Qu. Max. NAs
0.3334 0.6669 1.0000 0.8741 1.0000 1.0000 793
Assemble the full probability matrix
train_custom_knn() returns probabilities for retained reference cells, while predict_unknown_with_knn() returns probabilities for predicted cells. They can be combined and aligned to the cells present in the updated object.
full_prob_mat <- rbind(
knn_reference$core_prob_mat,
knn_prediction$prob_mat
)
full_prob_mat <- full_prob_mat[colnames(knn_prediction$spe), , drop = FALSE]
dim(full_prob_mat)
summary(rowSums(full_prob_mat))
Min. 1st Qu. Median Mean 3rd Qu. Max.
1 1 1 1 1 1
Quantify uncertainty
The uncertainty calculation combines probability-distribution measures with a sample-aware spatial-discordance score.
uncertainty <- calculate_uncertainty(
full_prob_mat,
knn_prediction$spe,
sample_col = "sample_id",
k_spatial = 3
)
head(uncertainty)
cell_id entropy gini_impurity margin_uncertainty spatial_discordance
12_1 12_1 0.0000000 0.000000 0.0000000 0.3333333
12_2 12_2 0.0000000 0.000000 0.0000000 0.3333333
12_3 12_3 0.0000000 0.000000 0.0000000 0.3333333
12_4 12_4 0.0000000 0.000000 0.0000000 1.0000000
12_5 12_5 0.2768968 0.494965 0.6697531 0.3333333
12_6 12_6 0.0000000 0.000000 0.0000000 0.6666667
Compare labels
label_confusion_matrix(
knn_prediction$spe,
label_col1 = "cell_type_hard",
label_col2 = "knn_label_filled"
)
v2
v1 Bcell BnTcell CD4 CD8 Myeloid Neutrophil Plasma_cell Stroma
Bcell 220 20 5 3 30 0 0 6
BnTcell 265 1209 502 355 49 0 0 8
CD4 0 0 4 0 0 0 0 0
CD8 0 4 2 78 3 0 0 0
Myeloid 83 37 77 43 330 0 2 28
Neutrophil 8 0 1 1 33 0 0 0
Plasma_cell 0 0 1 0 2 0 0 0
Stroma 1 1 2 2 4 0 0 0
Treg 0 5 159 0 11 0 0 0
Tumor 0 0 0 0 1 0 0 0
Unassigned 0 0 0 0 0 0 0 0
Uncertain 77 114 76 38 126 0 0 42
v2
v1 Treg Tumor Unassigned Uncertain
Bcell 1 0 11 0
BnTcell 84 0 34 0
CD4 1 0 0 0
CD8 0 0 0 0
Myeloid 13 0 41 0
Neutrophil 3 0 8 0
Plasma_cell 0 0 0 0
Stroma 0 0 1 0
Treg 44 0 7 0
Tumor 0 0 0 0
Unassigned 0 0 0 0
Uncertain 16 0 31 0
plot_labelled_cells(
knn_prediction$spe,
col_label = "knn_label_filled",
image_col = "image_name"
)
Other classifiers
cytoGateR also provides random-forest and optional Torch-based deep-learning classifiers. They use the same core-label and unknown-cell workflow. The following production alternatives are not evaluated during vignette building.
set.seed(1)
rf_reference <- train_custom_randomforest(
spe,
label_col = "core_group",
unknown_label = "Unassigned",
cv_folds = 5,
repeats = 10
)
dl_reference <- train_custom_dl(
spe,
label_col = "core_group",
unknown_label = "Unassigned",
epochs = 50,
cv_folds = 5,
repeats = 3
)
R version 4.6.2 (2026-10-29)
Platform: x86_64-pc-linux-gnu
Running under: Ubuntu 26.04.1 LTS
Matrix products: default
BLAS: /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3
LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.32.so; LAPACK version 3.12.0
locale:
[1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
[3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
[5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
[7] LC_PAPER=en_US.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
time zone: Etc/UTC
tzcode source: system (glibc)
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] cytoGateR_0.99.1
loaded via a namespace (and not attached):
[1] SummarizedExperiment_1.45.0 gtable_0.3.6
[3] rjson_0.2.23 xfun_0.63
[5] ggplot2_4.0.5 ggrepel_0.9.8
[7] Biobase_2.75.1 lattice_0.23-1
[9] vctrs_0.7.3 tools_4.6.2
[11] generics_0.1.4 parallel_4.6.2
[13] stats4_4.6.2 proxy_0.4-29
[15] tibble_3.3.1 pkgconfig_2.0.3
[17] Matrix_1.7-6 RColorBrewer_1.1-3
[19] pals_1.10 S7_1.0.0
[21] S4Vectors_0.53.1 lifecycle_1.0.5
[23] compiler_4.6.2 farver_2.1.2
[25] ggforce_0.6.0 mapproj_1.2.12
[27] codetools_0.2-20 Seqinfo_1.5.0
[29] graphlayouts_1.3.0 maps_3.4.4
[31] htmltools_0.5.9 sys_3.4.3
[33] buildtools_1.0.0 yaml_2.3.12
[35] pillar_1.11.1 tidyr_1.3.2
[37] MASS_7.3-66 BiocParallel_1.49.0
[39] SingleCellExperiment_1.37.1 cachem_1.1.0
[41] DelayedArray_0.41.0 dbscan_1.3.0
[43] viridis_0.6.5 magick_2.9.1
[45] abind_1.4-8 mclust_6.1.4
[47] tidyselect_1.2.1 digest_0.6.39
[49] dplyr_1.2.1 purrr_1.2.2
[51] labeling_0.4.3 maketools_1.3.2
[53] polyclip_1.10-7 fastmap_1.2.0
[55] grid_4.6.2 colorspace_2.1-4
[57] cli_3.6.6 SparseArray_1.15.0
[59] magrittr_2.0.5 S4Arrays_1.15.0
[61] dichromat_2.0-1 ggraph_2.2.2
[63] tidygraph_1.3.1 withr_3.0.3
[65] scales_1.4.0 rmarkdown_2.32
[67] XVector_0.55.0 matrixStats_1.5.0
[69] igraph_2.3.4 otel_0.3.0
[71] gridExtra_2.3.1 SpatialExperiment_1.25.0
[73] memoise_2.0.1 evaluate_1.0.5
[75] knitr_1.52 GenomicRanges_1.67.0
[77] IRanges_2.49.0 viridisLite_0.4.3
[79] rlang_1.3.0 Rcpp_1.1.2
[81] glue_1.8.1 tweenr_2.0.3
[83] BiocGenerics_0.61.1 jsonlite_2.0.0
[85] R6_2.6.1 MatrixGenerics_1.27.0