<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ariel Robert Mutebi on Medium]]></title>
        <description><![CDATA[Stories by Ariel Robert Mutebi on Medium]]></description>
        <link>https://medium.com/@arielmutebi?source=rss-61fa688d1dee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rynjTfJeuRPpiufgyk3wAw.jpeg</url>
            <title>Stories by Ariel Robert Mutebi on Medium</title>
            <link>https://medium.com/@arielmutebi?source=rss-61fa688d1dee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:47:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arielmutebi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I Replicated a Pathology Foundation-Model Workflow]]></title>
            <link>https://medium.com/@arielmutebi/how-i-replicated-a-pathology-foundation-model-workflow-a1c3c23dd778?source=rss-61fa688d1dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1c3c23dd778</guid>
            <category><![CDATA[digital-pathology]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[foundation-models]]></category>
            <category><![CDATA[vector-embeddings]]></category>
            <dc:creator><![CDATA[Ariel Robert Mutebi]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 08:31:26 GMT</pubDate>
            <atom:updated>2026-11-14T15:25:18.307Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*VCjGOnTzma5wl5cM7ztLmQ.jpeg" /><figcaption>An up-close look at gastrointestinal mucosa (<a href="https://www.hopkinsmedicine.org/news/articles/2024/04/a-pathology-revolution-one-slide-at-a-time">source</a>)</figcaption></figure><h3>TL;DR</h3><p>I replicated a core workflow of pathology foundation models to understand how modern machine learning models are built, tested, and benchmarked. Using a pathology-pretrained model and a simple linear classifier on the PatchCamelyon dataset, I got a test AUC of 0.9385 with only 300 labels, against 0.8752 for a convolutional neural network that I trained from scratch on all 30,000 labels. The biggest thing that I learned was that thorough evaluation — meaning several seeds, a held-out test set and a graph instead of one number — matters just as much as the model code.</p><ul><li>Youtube video: <a href="https://youtu.be/L34PwqBHJxw?si=zImUKm0julRryGAr">https://youtu.be/L34PwqBHJxw?si=zImUKm0julRryGAr</a></li><li><strong>The Kaggle Notebook:</strong> <a href="https://www.kaggle.com/code/arielmutebi/my-first-tks-build">https://www.kaggle.com/code/arielmutebi/my-first-tks-build</a></li></ul><h3>1. Why this matters</h3><p>Computational pathology is trying to identify cancer in microscope images of tissue, reliably and at scale. Today, the prevailing approach is to train a separate model for each task on images that experts have labelled, but that struggles because every label costs an expert’s time. I chose to replicate the foundation-model workflow since it is the leading answer to that problem: pretrain once on huge amounts of unlabeled images, then adapt cheaply with few labels [2]. I like to think of the foundation model as an infant who already knows what objects in their home looks like, and the adapting is simply teaching the infant the nouns to label those objects. This is distinct from training a model from scratch so that it has to learn what the “objects” look like and learn their labels at once.</p><h3>2. What I replicated</h3><p>The original work is <em>Towards Large-Scale Training of Pathology Foundation Models</em><strong> </strong>[1]. They compared randomly-initialized, ImageNet-pretrained and pathology-pretrained vision transformers on downstream tasks, using an open-source evaluation framework that includes PatchCamelyon. My goal was to reproduce that kind of three-way comparison on one task, and to understand how a frozen pretrained model with a classifier on top works.</p><p>I didn’t train a foundation model, which needs far more data and compute than a free notebook offers. I reproduced the part a practitioner does: adapting one that already exists.</p><p><strong>How the workflow works, in simple terms</strong>: A label is the correct answer attached to a training example. Here, each PatchCamelyon image patch receives a binary label: 1 if its central 32 × 32 pixel region contains at least one pixel of tumour tissue, and 0 otherwise. Labels are expensive because each one needs an expert, while the images themselves are cheap.</p><p>A foundation model sidesteps this. It is pretrained with self-supervised learning on huge numbers of images with no labels, so it learns what a tissue looks like without anyone telling it which patches are tumours. Using one takes three steps:</p><ol><li><strong>Freeze a pretrained model </strong>so its weights never change.</li><li><strong>Run your images through it to get embeddings</strong>: Embeddings are numerical representations of images, expressed as vectors in a high-dimensional space. They encode visual information learned by the model, such that images with similar learned characteristics may have nearby representations</li><li><strong>Train a tiny classifier, called a linear probe</strong>, on those embeddings using your own labels: I think of a linear probe as a knife that cuts through the vector space, separating semantically similar data points into distinct categories.</li></ol><p>The interesting question is whether the representations learned during pretraining are sufficiently useful that a simple classifier, trained with relatively few labelled examples, can successfully distinguish tumour-positive from tumour-negative tissue patches.</p><h3>3. Methods: How I did it</h3><p><strong>Tools and stack:</strong> A Kaggle notebook with a free GPU, using Python, PyTorch, scikit-learn, h5py, transformers, and timm . Pretrained models came from HuggingFace.</p><p><strong>How it works.</strong> Both routes start from the same patches and end at the same test set.</p><figure><img alt="Methods: two routes from a patch to a test score" src="https://cdn-images-1.medium.com/max/1024/1*ctjbNLPpgqO26TI8NXIJ0w.png" /></figure><p>Route A learns everything from my labels. Route B borrows a frozen model’s embeddings and learns only a linear classifier on top.</p><h4>Key components and what each does</h4><ul><li><strong>Dataset and loader</strong>: Each stored patch becomes a tensor with channels first before image dimensions, pixel RGB values rescaled from 0–255 to 0–1 because training is stabler on small values, served in batches of 128.</li><li><strong>Small CNN: </strong>four convolution blocks progressively extract visual patterns from the images. Each block applies: a convolution to detect patterns; batch normalization to stabilize training; ReLU activation so that negative values (caused by the convolution not finding a feature) are discarded and features stack properly; and max pooling which takes the maximum value in a 2 × 2 pixel sliding window in order to halve the image dimensions while retaining the strongest feature signal. As an image progresses through the CNN, its channels increase from 3 which encode the RGB values of each pixel, to 128 channels encoding features that the model identified. Meanwhile, the dimensions reduce from 96 × 96 to 6 × 6 pixels. Finally, adaptive average pooling compresses the 128 feature maps on a 6 × 6 grid into just 128 numbers. Then, a linear layer takes those 128 numbers to output a number representing the model’s prediction score.</li><li><strong>Training loop</strong>: The model processes the training images in batches of 128. For each batch, it produces prediction scores (logits), which are compared against the true labels using binary cross-entropy loss. This measures how far the predictions are from the correct answers. The Adam optimizer then uses backpropagation to calculate how the model’s weights should change to reduce this error, and updates them accordingly. This process repeats for five epochs (complete passes through the training dataset). After each epoch, I evaluate the model on the validation set using ROC-AUC, which measures how well it distinguishes tumor-positive from tumor-negative patches.</li><li><strong>DINOv2-small embedder:</strong> I load the pretrained facebook/dinov2-small vision transformer from HuggingFace and freeze its weights, meaning it cannot learn or change during my experiment. Before passing images through it, I resize the 96 × 96 patches to 224 × 224 pixels and normalise their RGB values using ImageNet&#39;s mean and standard deviation. This puts the images into the format expected by the pretrained model. DINOv2 then processes each patch and produces a pooled embedding. Finally, I repeat this for the training, validation and test sets, then save the embeddings for downstream classification [3].</li><li><strong>Kaiko ViT-S/16 embedder:</strong> I load the pathology-pretrained Kaiko Vision Transformer (1aurent/vit_small_patch16_224.kaiko_ai_towards_large_pathology_fms) using timm and freeze its weights. As with DINOv2, I resize the 96 × 96 patches to 224 × 224 pixels, and I normalise the RGB channels but with a different mean and standard deviation from the model documentation. Again, I extract and save embeddings for the training, validation and test sets for downstream classification [4].</li><li><strong>Linear probe:</strong> I standardize the embeddings using StandardScaler, centring each feature around zero and scaling it to unit variance. I then fit a logistic regression classifier on the training embeddings. In my earlier analogy, logistic regression is the “knife” that cuts through the embedding space, learning a linear decision boundary to separate tumour-positive from tumour-negative patches. The pretrained encoders remain frozen; only the classifier is trained. I evaluate its performance on the validation and test sets using ROC-AUC.</li><li><strong>Subset sampler:</strong> To investigate how performance changes with the amount of labelled training data, I train the models using 1%, 5%, 10%, 25% and 100% of the 30,000 training patches. For each fraction, I use a seeded random shuffle to select a reproducible subset of patches. I repeat the experiment with three different seeds and use identical subsets for the CNN and both linear probes, ensuring a fair comparison. I report the mean and standard deviation of test ROC-AUC across the three runs.</li></ul><h4>How I tested that it works</h4><p>I tested that it works by plotting the raw tissue images with their labels to ensure that the dataset contained what I expected. I validated the file sizes. I made sure that the class balance was roughly equal (validation 16,399 vs 16,369, test 16,391 vs 16,377, training subset 14,967 vs 15,033). And I ran the notebook multiple times to ensure that it was reproducible. You too can run <a href="https://www.kaggle.com/code/arielmutebi/my-first-tks-build">the notebook</a>, or copy it and experiment on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*drOwf06BGWOSkZo0iyPgcw.png" /><figcaption>Checking through the PatchCamelyon dataset.</figcaption></figure><h4><strong>Data and inputs</strong></h4><p>PatchCamelyon has 327,680 patches of 96 × 96 pixels from lymph node sections, labeled for metastatic tissue, under a CC0 licence. I used a community copy on Kaggle with uncompressed HDF5 files (images under key x, labels under y). My training set was the first 30,000 training patches (14,967 normal, 15,033 tumor), evaluated on the full validation and test splits of 32,768 patches each.</p><h3>4. Results</h3><p>I found that the pathology-pretrained probe beat the CNN at every training-set size, and with just 300 labels it scored 0.9385 test AUC against 0.8752 for the CNN trained on all 30,000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*Vgl1Tp1h0NqV9f9SzK5kfg.png" /></figure><p>Four other things stand out in my results:</p><ul><li><strong>Pathology pretraining helps most when labels are scarce.</strong> The kaiko probe’s lead over the generic DINOv2 probe was about 0.06 AUC at 300 labels and about 0.04 at 30,000. Both are small vision transformers with the same classifier and labels, so the main difference is what they were pretrained on.</li><li><strong>The generic probe sat in between.</strong> DINOv2 was clearly ahead of the CNN from 3,000 labels up, and about tied with it at 1,500.</li><li><strong>The CNN stalled.</strong> It scored 0.888 at 1,500 labels and 0.875 at 30,000, so more labels didn’t help. At 300 labels its score swung by ±0.037 between seeds, against ±0.005 for the kaiko probe.</li><li><strong>The probes held up on the test set, and the CNN didn’t.</strong> The CNN scored about 0.92 on validation but 0.875 on test, while the probes scored about the same on both. I didn’t test why. One explanation is that the CNN learns slide-specific cues, such as staining, that don’t carry over to the test slides.</li></ul><h3>5. What went wrong and how I fixed it</h3><p><strong>1. My search for the image files came back empty.</strong></p><ul><li><strong>What I tried:</strong> I looked for the file names I expected from the original PCam release.</li><li><strong>What worked:</strong> Listing every file with its size. 32,768 × 96 × 96 × 3 bytes is about 906 MB, which matched validation_split.h5, so the images were there under different names.</li></ul><p><strong>2. One giant notebook cell was slow to rerun.</strong></p><ul><li><strong>What I tried:</strong> Rerunning the whole cell after each change, which reloaded about 95,000 images every time.</li><li><strong>What worked:</strong> Splitting the notebook into cells (load data, build loaders, define model, train, evaluate), so a change reruns only its own cell.</li></ul><p><strong>3. CNN scores swung between seeds and dipped at epoch 4 in every run.</strong></p><ul><li><strong>What I tried:</strong> Training the same CNN with different seeds and comparing validation and test AUC.</li><li><strong>What worked:</strong> Reporting means and standard deviations over three seeds with a fixed recipe, and never picking a best epoch. I did not find the cause of the dip.</li></ul><p><strong>4. Small training subsets would get too few weight updates in 5 epochs.</strong></p><ul><li><strong>What I tried:</strong> Considering giving every subset the same 5 epochs.</li><li><strong>What worked:</strong> Giving every run about the same number of updates (1,175), so the CNN’s weak spots would not just reflect undertraining.</li></ul><h3>6. Limitations</h3><p>My version is limited because it uses one dataset, a 30,000-patch slice of the training set, three seeds per point, and a bare-bones CNN with no augmentation or tuning. I can’t yet claim that pathology pretraining alone explains the gap between the two probes, that the CNN is inherently worse rather than under-tuned, or that any of this holds beyond PatchCamelyon or in a clinic. To be more confident, I would need more seeds, a tuned CNN with augmentation, the full training set, a second dataset, and a direct check of the gap between validation and test.</p><p>Four more caveats worth knowing:</p><ul><li><strong>Scale and resolution.</strong> I upscaled 96-pixel patches to 224. PCam was sampled at about 1.0 micron per pixel, while pathology models are typically trained on finer tiles; H-optimus-0’s model card, for example, asks for 0.5 microns per pixel.</li><li><strong>Overlap not verified.</strong> Kaiko’s published models were pretrained on TCGA slides [2], and PCam is derived from Camelyon16 [1]. These are different collections, but I didn’t check that nothing overlaps.</li><li><strong>The two pretrained models differ in more than data.</strong> Their training methods may differ too, so I credit pathology pretraining as the main difference, not the only one.</li></ul><h3>7. What I learned</h3><p>The most surprising thing was how much a model’s pretraining mattered compared with how much labeled data I gave it: with 300 labels, a probe on a pathology-pretrained model beat a CNN trained on 30,000.</p><p>If I did it again, I would treat the baseline as part of the experiment, not a warm-up. I built the CNN once, bare-bones, and measured everything against it, so part of the pretrained models’ lead may just be the CNN’s weakness, and I’d give it as much care as the models I expected to win.</p><h3>8. Next Steps</h3><p>For my next step, I want to give the CNN a fairer fight by adding random flips and 90-degree rotations (tissue has no natural up) and tuning its learning rate, which would test whether its flat learning curve reflects the model’s limits or my bare-bones training setup.</p><p>After that:</p><ul><li>Investigate the gap between validation and test. My CNN scored about 0.92 on validation and about 0.88 on test, while the probes showed no such gap. I suspect differences between slides, such as staining, and the dataset’s metadata files may show whether the splits come from different slides.</li><li>Try a larger pathology model such as H-optimus-0, which is gated on Hugging Face and lists an Apache-2.0 licence.</li><li>Move from patches to whole slides, which is closer to how pathologists work.</li></ul><h3>References</h3><ol><li>Veeling, B. S., Linmans, J., Winkens, J., Cohen, T., Welling, M., Rotation Equivariant CNNs for Digital Pathology, Springer (preprint arXiv:1806.03962), 2018, <a href="https://doi.org/10.1007/978-3-030-00934-2_24">https://doi.org/10.1007/978-3-030-00934-2_24</a></li><li>kaiko.ai, Aben, N., de Jong, E. D., Gatopoulos, I., Känzig, N., Karasikov, M., Lagré, A., Moser, R., van Doorn, J., Tang, F., Towards Large-Scale Training of Pathology Foundation Models, arXiv:2404.15217, 2024, <a href="https://arxiv.org/abs/2404.15217">https://arxiv.org/abs/2404.15217</a></li><li>Oquab, M. et al., DINOv2: Learning Robust Visual Features without Supervision, arXiv:2304.07193, 2023, <a href="https://arxiv.org/abs/2304.07193">https://arxiv.org/abs/2304.07193</a></li><li>kaiko.ai, ViT-S/16 model card (a third-party mirror of kaiko’s public weights), Hugging Face, 2024, <a href="https://huggingface.co/1aurent/vit_small_patch16_224.kaiko_ai_towards_large_pathology_fms">https://huggingface.co/1aurent/vit_small_patch16_224.kaiko_ai_towards_large_pathology_fms</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1c3c23dd778" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Phantom Cells: The Segmentation Problem Hiding Inside Spatial Biology]]></title>
            <link>https://medium.com/@arielmutebi/phantom-cells-the-segmentation-problem-hiding-inside-spatial-biology-032972b3dda3?source=rss-61fa688d1dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/032972b3dda3</guid>
            <category><![CDATA[the-knowledge-society]]></category>
            <category><![CDATA[spatial-transcriptomics]]></category>
            <dc:creator><![CDATA[Ariel Robert Mutebi]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 00:03:13 GMT</pubDate>
            <atom:updated>2026-10-28T07:12:40.426Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*1BsNmJvBtG4GtVYl-kgk2Q.png" /></figure><p>Where does a cell end? Accurately answering this question is fundamental to the field of spatial biology, and the consequences of getting it wrong can be far-reaching. In spatial transcriptomics, which aims to understand the RNA expression profiles of individual cells while retaining data about their precise location in the tissue, imprecise cell segmentation can cause RNA transcripts to be misattributed to neighboring cells of a different type, leading to “phantom cells” — whose expression profiles are a confusing mix of profiles from different cell types. [1]</p><p>In a very recent Nature Methods benchmark of segmentation methods, researchers analyzed three mouse brain datasets generated using three spatial transcriptomics technologies. They picked consistently expressed genes from three well-annotated brain cell types — astrocytes, endothelial cells and microglia. They quantified transcript misattribution by looking at the expression of “negative markers”, genes not expected to be expressed in a given cell type. Particularly, an astrocyte marker <em>Igfbp5</em> in endothelial cells and an endothelial marker <em>Flt1</em> in microglia. And they measured for each cell, the distance to its nearest neighbour of a different type, then the proportion of cells expressing that neighbor&#39;s marker at each distance. A small Euclidean distance and a high percentage of negative markers points to transcript misattribution. The results are in the graph below [1]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*IpENe0Y9r2czDQidwCRdxA.png" /></figure><p>These results show that transcript misattribution can affect up to 10 to 15% of cells. The benchmark continues to discuss how this issue propagated to downstream analysis of ligand-receptor interactions in the mouse brain.</p><h3>How Segmentation Works</h3><p>The approaches to cell segmentation have evolved over time. Roughly over these generations:</p><h3>Generation one: Watershed</h3><p>Watershed is the oldest method in the benchmark, and its logic is inspired by geography. A grayscale image is treated as a terrain, with each pixels gray value as its elevation. Imagine flooding the landscape, starting from the bottom of each valley. Water rises from each valley, and wherever water from two different valleys would meet, a dam is built. When the flooding finishes, the dams are the watershed lines, and the basins they enclose are the segmented regions [2].</p><p>Early implementations were impractical. Vincent and Soille’s 1991 paper described a much faster approach: sort all the pixels by gray value, then flood level by level using a first-in-first-out queue of pixels. Their examples were an MRI scan of a spine and a terrain elevation model, not cells. [2]</p><h4>How Watershed is applied to cell segmentation</h4><ol><li><strong>Preprocessing: </strong>the nuclei are stained with DAPI, a fluorescent dye that binds to DNA. This renders each nucleus a bright blob on a dark background. The image is converted into a single-channel grayscale.</li><li><strong>Separating nuclei from the background: </strong>Stain brightness is uneven, so a single fixed cutoff would either admit background haze or miss dim nuclei. The pipeline instead uses multi-Otsu thresholding, involving building a histogram of pixel brightness and picking the cutoff that splits pixels into the most tightly clustered groups [3].</li><li><strong>Smoothing and finding seeds:</strong> the stain is then blurred with a Gaussian filter, and the local brightness maxima inside the mask become the seeds for which flooding starts [1]. Smoothing matters because noise creates spurious maxima, which would cause the algorithm to split the nucleus (as it would wrongly take each maxima to be the center of a different nucleus). Vincent and Soille found that over-segmentation in watershed often comes from noise [2]. The filter size is a trade-off: too small and noise survives, too large neighboring nuclei blur into one seed.</li><li><strong>Flooding:</strong> Watershed grows regions outward from the seeds until neighboring regions meet, with boundaries placed by intensity gradients in the stain image [1]. The output is a labelled region for each <strong>nucleus</strong> [1]. This is where the method’s central limit lies: it segments nuclei, not whole cells.</li></ol><h4>The Nucleus-to-Cytoplasm Gap and Naive Expansion</h4><p>Because DAPI stain only labels cell nuclei, Watershed leaves the surrounding cytoplasm entirely dark. Yet in spatial transcriptomics, the vast majority of functional mRNA resides outside the nucleus in the cytoplasm.</p><p>To bridge this gap, early spatial pipelines introduced a secondary heuristic: expanding the Watershed nuclear mask outward by a fixed distance buffer (typically 5 to 10 micrometers) until it hit an arbitrary cutoff or met the expanding buffer of a neighboring cell [1].</p><p>This heuristic fails in real biological tissue for three primary reasons:</p><ol><li><strong>Morphological Arbitrariness</strong>: Real cells are rarely neat, concentric spheres. Neurons, astrocytes, endothelial cells and the like possess irregular, elongated, or interdigitating processes [1]. Enclosing them in uniform spherical buffers misrepresents their actual physical boundaries.</li><li><strong>The Density Dilemma:</strong> In dense tissue regions (such as the brain cortex or solid tumors), a fixed expansion buffer aggressively spills across neighboring membranes [1]. This directly causes transcript misattribution.</li><li><strong>Sensitivity to staining and noise: </strong>As Vincent and Soille highlighted in their 1991 paper, watershed algorithms are inherently vulnerable to image noise, which creates spurious local intensity maxima and leads to severe over-segmentation [2]. Furthermore, multi-Otsu thresholding assumes uniform background-to-signal contrast [3] — an ideal state rarely achieved across variable tissue slides [1].</li></ol><p>In summary, this first-generation approach to cell segmentation treated it as a static geometry problem, forcing complex biological structures into rigid intensity topographies. To bridge the gap from nuclear seeds to true cell boundaries, the field needed models that could <em>learn</em> what a cell looks like across diverse contexts — paving the way for deep learning.</p><h3>Generation 2: Deep Learning and Morphological Priors (U-net and Cellpose)</h3><p>To overcome the limitations of first-generation algorithms, computer vision underwent a foundational paradigm shift: moving away from heuristics toward deep neural networks that learn complex visual patterns directly from supervised learning of thousands of annotated example images [6]. Rather than assuming what a cell should look like mathematically, deep learning models learn the rich, varied morphological priors of real biological tissue.</p><h4>Demystifying the Machinery: What is a Convolutional Neural Network?</h4><p>To understand how modern segmentation algorithms operate, we muct look at their core building block: the <strong>Convolutional Neural Network (CNN)</strong> [1][5].</p><h4>1. The Dimensionality Problem</h4><p>A standard neural network is designed to take a row from a spreadsheet (e.g. [Age, Income, Credit Score, Years at Job] ) and output a prediction (e.g. Risk of Default ). Each input variable is an input node (making up the input layer), and it is connected to every individual neuron in the subsequent layer (the hidden layer). The final prediction is formed at the output layer. In model training, the algorithms’ prediction can be compared against the actual answer via a loss function. And the weights in the hidden layer can then be adjusted by backpropagation.</p><p>This pipeline is perfect for domains with a lot of tabular data, like finance, but it completely falls apart when a microscopic image is forced through it. Think about it: a single-channel image is a 2D matrix of pixel brightness values. Because a standard neural network requires a 1D vector of inputs, an image can only be pushed into the network by “flattening” the image — appending Row 2 to the end of Row 1, Row 3 onto Row 2, and so on. A 512 × 512 image would turn into a massive array of <strong>262,144</strong> input numbers! And connecting those inputs to a hidden layer of just 1,000 neurons would require over <strong>260 million individual weight parameters </strong>for a single layer! This explosive parameter growth makes standard neural networks prohibitively expensive to train for biomedical imaging applications and prone to severe overfitting.</p><p>More critically, unrolling a 2D grid into a 1D line destroys the spatial relationships that define biological structures. Two pixels that touch vertically in adjacent rows of an image end up separated by hundreds of positions down the flattened 1D array, and the network ends up treating them as independent variables. And, because every input position has its unique set of weights, this means that a standard network lacks spatial memory across coordinates. If the network learns what a circular cell nucleus looks like in the top-left corner of the slide, those learned weights are useless if the exact same nucleus appears in the bottom-right corner. The network would have to re-learn what a nucleus looks like at every single coordinate on the slide.</p><p>To process microscopic tissue images, computer vision needed an architecture that leaves the 2D grid intact and reuses learnable parameters efficiently across the entire image — giving rise to the Convolutional Neural Network.</p><h4>2. The Sliding Filter (Kernel Convolution)</h4><p>CNNs inspect images using small, two-dimensional grids of numbers called <strong>kernels</strong> or <strong>filters </strong>(typically 3 × 3 pixels). Imagine sliding a tiny 3 × 3 window across an image pixel by pixel. At each position, the neural network multiplies the filter’s internal weights by the underlying pixel values and sums them into a single output value [4].</p><ul><li>A filter with uniform positive weights calculates a local moving average, producing a <strong>blur</strong> [4].</li><li>A filter with positive weights on one side and negative weights on the other calculates local contrast differences, acting as an <strong>edge detector</strong> [4].</li></ul><p>In classic image processing, computer scientists manually calculated these filter weights. In a CNN, the network learns the optimal numbers inside these filters automatically from training data through backpropagation [4].</p><h4>3. Feature Channels and the Visual Hierarchy</h4><p>A single convolutional layer does not apply just one filter; it applies dozens in parallel, generating a stack of output maps called <strong>feature channels</strong> [5]. By stacking convolutional layers on top of one another, CNNs build a hierarchical understanding of visual data:</p><ul><li><strong>Early Layers: </strong>Learn simple low-level primitives, such as vertical edges, membrane lines, and bright-to-dark contrast steps.</li><li><strong>Middle Layers: </strong>Combine edge primitives into mid-level textures, corners, and curved boundaries.</li><li><strong>Deep Layers: </strong>Combine textures into high-level biological concepts, recognizing whole nuclear blobs, cytoplasmic bodies, and cellular organization.</li></ul><h3>The Architectural Breakthrough: U-Net</h3><p>Traditional CNNs were designed for image classification — reducing an entire photo down to a single label (e.g., “cell” vs. “no cell”) [5]. For biomedical segmentation, however, every individual pixel must be assigned a label [5]. Early patch-based sliding window networks were computationally sluggish and struggled to balance local detail and broader spatial context [5].</p><p>In 2015, Olaf Ronneberger and colleagues introduced <strong>U-Net</strong>, a fully convolutional architecture specifically designed for biomedical segmentation [6]. U-Net arranges its 23 convolutional layers into a symmetric, “U-shaped” encoder-decoder structure [5].</p><ol><li><strong>The Contracting Path (Encoder / Down-sampling):</strong> The network repeatedly applies 3 × 3 convolutions followed by 2 × 2 <strong>max-pooling</strong> operations. Max-pooling keeps only the maximum pixel value in each 2 × 2 block, halving the spatial resolution while doubling the number of feature channels. Zooming out allows deeper layers to cover a wide field of view, capturing broader tissue context [5].</li><li><strong>The Bottleneck:</strong> At the base of the “U”, the image is compressed into its lowest spatial resolution but highest feature depth (e.g., 1024 channels). Here, the network holds a highly abstract summary of the entire region. [5]</li><li><strong>The Expansive Path (Decoder / Up-sampling):</strong> The network applies 2 × 2 “up-convolutions” that double the spatial dimensions while halving feature channels, gradually expanding the feature maps back to the original image resolution [5].</li><li><strong>Skip Connections: </strong>Because spatial location data gets blurred during encoder down-sampling, U-Net introduces <strong>skip connections</strong>. These copy high-resolution feature maps directly from the encoder layers over to the corresponding decoder layers [5]. By combining the “what” provided by the feature channels with the “where” provided by the unblurred early features, U-Net achieves pinpoint boundary localization. [5]</li><li><strong>Separating Touching Cells via Weighted Loss</strong>: to prevent adjacent cells from merging into a single blob, U-Net introduced a weighted loss map during training. Background pixels located in the narrow gaps between touching cells were assigned heavy penalty weights, forcing the network to learn strict cell-to-cell separation boundaries [5].</li></ol><h3>The Cellular Refinement: Cellpose</h3><p>While U-Net excelled at segmenting uniform objects, standard deep learning models struggled with the extreme shape diversity of whole cells — such as branching neurons, elongated muscle fibers, and crowded epithelial tissues. Standard approaches attempted to predict static binary masks (i.e. bright represents a cell in this region) or arbitrary instance numbers (cell 1, 2, etc.). These fail when complex cell processes overlap or curve around neighbors.</p><p>In 2020, Carsen Stringer and colleagues published <strong>Cellpose</strong>, a generalist segmentation framework built on two key advancements: a novel continuous geometric representation and a deeply enhanced U-net backbone. [6]</p><h4>1. Heat Diffusion and Vector Spatial Flows</h4><p>Instead of predicting cell boundaries directly, Cellpose converts manually-annotated training cells into a <strong>reversible vector flow field</strong> using a simulated heat diffusion process:</p><ol><li><strong>Simulated Heat Diffusion:</strong> A heat source is placed at the topological center of every annotated cell body, allowing heat to diffuse throughout the cell mask until it reaches an equilibrium distribution. [6]</li><li><strong>Spatial Gradients:</strong> Calculating horizontal (X) and vertical (Y) spatial derivatives of this equilibrium heat map creates a continuous vector flow field. Every pixel inside a cell gets a vector pointing “uphill” toward the cell center — even curving around corners for cell shapes with extensions [6].</li><li><strong>Null Background</strong>: Pixels outside cell bodies are assigned a gradient of zero [6].</li></ol><h4>2. The Cellpose Architecture</h4><p>To predict these continuous vector fields across diverse tissue types, Cellpose enhances the classic U-Net architecture with three key deep learning innovations:</p><ul><li><strong>Deepening the Network with Residual Blocks: </strong>In Standard deep networks, backpropagation signals fade as they travel through dozens of layers (the vanishing gradient problem [6]). Residual shortcuts allow training signals to flow backward unhindered. This let Cellpose double its U-Net depth [6].</li><li><strong>Additive Feature Fusion:</strong> Classic U-Net fuses spatial details from its contracting path to its expanding path by concatenating feature channels side-by-side, doubling memory footprint [6]. Cellpose replaces feature concatenation with direct element-wise addition on up-sampling passes, minimizing parameter counts while preserving boundary localization.</li><li><strong>Dynamic Adaptation via Image Style Vectors:</strong> Microscopic slides vary drastically in lighting, contrast, and staining modality [6]. At the network’s deep bottleneck, Cellpose applies global average pooling across feature maps to extract a 256-dimentional vector called a “style vector”. This vector summarizes the overall visual texture of the slide and is broadcast into every up-sampling stage, enabling the network to dynamically adjust its internal predictions based on the specific imaging modality [6].</li></ul><h4>3. Output Maps and Inference (“Following the Flows”)</h4><p>For any raw microscopic input tile, Cellpose output <strong>three prediction maps</strong>:</p><ol><li><strong>Horizontal Gradient Flow Map (X)</strong></li><li><strong>Vertical Gradient Flow Map (Y)</strong></li><li><strong>Cell Probability Map</strong> (a sigmoid score indicating whether a pixel lies within a cell body)</li></ol><p>During inference, Cellpose selects all pixels with a predicted cell probability greater than 0.5. Each pixel then “follows the flows” — iteratively stepping along the predicted X and Y gradient vectors. Because all vectors within a given cell body point toward that cell’s topological center, all pixels belonging to the same cell converge to the exact same point. Pixels that share a common convergence point are grouped and labeled as one cell.</p><h3>The Limitations of Second-Generation Approaches</h3><p>Deep learning models like Cellpose represent a massive leap forward over classical Watershed, successfully segmenting complex cytoplasm across diverse imaging modalities. Yet, when deployed inside high-density spatial transcriptomics pipelines, they run into severe structural limitations:</p><ol><li><strong>Blindness to Unstained Cytoplasm</strong>: Deep vision models are bounded by optical staining. In many spatial transcriptomics experiments, only nuclear stains (like API) or partial membrane markers are used. When cytoplasm is dim, unlit, or non-fluorescent deep visual models cannot predict boundaries for structures they cannot see [7].</li><li><strong>The 2D Projection Artifact:</strong> Tissue sections are 3D volumes projected onto a 2D plane. Cells in complex tissues interdigitate and stack vertically. A 2D convolutional network drawing flat polygon boundaries inevitably slices through overlapping cell bodies, leading to transcript misattribution. [7]</li><li><strong>Ignoring the Primary Data Layer:</strong> Crucially, computer vision models treat spatial transcriptomics as a pure image-processing task. They draw boundaries based on light intensity, completely ignoring the rich, high-dimensional mRNA transcript coordinates scattered across the slide [7].</li></ol><p>By relying strictly on visual cues, second-generation approaches leave a wealth of spatial molecular evidence completely untapped — setting the stage for…</p><h3>Generation 3: Molecular and Multimodal Approaches (Baysor, BIDCell, and Segmentation-Free)</h3><p>The first and second generations shared a fundamental assumption: that cell segmentation is an <strong>image processing problem</strong>. They attempted to solve it by taking a 2D optical slide, analyzing pixel brightness or visual gradients, drawing polygon boundaries, and only then asking, <em>“Which mRNA transcripts happen to fall inside this polygon?”</em></p><p>The third generation flips this logic entirely. In spatial transcriptomics, the primary physical measurements are not pixels — they are <strong>discrete, high-dimensional mRNA transcript coordinates scattered in 3D space </strong>[8].</p><p>Rather than forcing molecular data into rigid visual boundaries, Generation Three asks: <strong>What if the spatial density, distribution, and gene composition of the mRNA molecules themselves define where a cell begins and ends?</strong> [8]</p><h3>Approach 1: Transcript-Informed Probabilistic Segmentation (Baysor)</h3><p>Introduced by Viktor Petukhov and colleagues in 2022, <strong>Baysor</strong> re-imagined cell segmentation as a statistical point-process problem [8].</p><p>Instead of treating mRNA coordinates as passive points inside a visual mask, Baysor models the entire dataset as a <strong>Bayesian Mixture Model combined with a Markov Random Field (MRF) </strong>[8].</p><h4>1. The Mathematical Framework</h4><p>Baysor models each cell as a joint probability distribution over two parameters:</p><ul><li><strong>Physical Location</strong>: Modeled as a <strong>Multivariate Normal distribution</strong> over the spatial coordinates of its constituent molecules [8].</li><li><strong>Transcriptional Identity</strong>: Modeled as a <strong>Categorical distribution</strong> over the gene identities of those molecules [8].</li></ul><h4>2. Spatial Clustering via Markov Random Fields (MRF)</h4><p>Because nearby transcripts naturally tend to originate from the same cell, Baysor incorporates an <strong>MRF prior</strong> into its Expectation-Maximization (EM) optimization [8]. The MRF acts as a spatial regularizer, ensuring that adjacent molecules are probabilistically encouraged to share the same cell label unless their transcriptomic identities strongly disagree [8].</p><h4><strong>3. Filtering Intercellular Background Noise</strong></h4><p>In physical tissue, unbound ambient RNA creates diffuse noise between cell bodies [8]. To prevent this noise from dragging cell boundaries outward, Baysor calculates the distance of each molecule to its <em>k</em>-th nearest neighbor. It models these distances as a two-component <strong>Gaussian Mixture Model</strong> (intracellular vs. background) via EM, explicitly filtering out ambient molecules before fitting cell bodies [8].</p><h4>4. Incorporating Image Priors via Confidence Parameters</h4><p>While Baysor can run purely on transcript coordinates, it can also accept auxiliary image masks (such as DAPI nuclear Watershed boundaries) as a probabilistic prior. Baysor introduces a <strong>prior segmentation confidence parameter </strong>(ranging from 0–1) [8].</p><ul><li>At confidence prior = 0, Baysor ignores the image mask entirely [8].</li><li>At confidence prior &gt; 0, Baysor uses the image mask to seed cell centres while reserving the flexibility to expand, reassign, or split disputed cytoplasm transcripts based on molecular co-expression [8].</li></ul><h4><strong>5. Known Limitations</strong></h4><p>As Petukhov et al. note, Baysor makes two central mathematical assumptions: that a cell’s transcriptional composition is homogeneous across its cytoplasm, and that cell shapes can be approximated by a bivariate normal distribution. Consequently, Baysor can struggle in dense tissue regions composed of transcriptionally identical cells (such as CA1 pyramidal neurons in the hippocampus), where transcript distributions become uniform and require nuclear image priors to resolve boundaries [8].</p><p>Furthermore, Baysor’s point-process optimization scales quadratically (O(N²)) in memory and runtime, making it hard to process massive tissue slices [10].</p><h3>Approach 2: Biologically-Informed Self-Supervised Deep Learning (BIDCell)</h3><p>While transcript-only methods excel when staining is poor, ignoring tissue morphology entirely means discarding valuable structural context. <strong>BIDCell</strong> (Fu et al., 2024) addresses this by combining deep learning image backbones with biological knowledge derived from single-cell RNA sequencing (scRNA-seq) reference atlases [9].</p><h4><strong>1. The Architecture: UNet 3+ Backbone</strong></h4><p>BIDCell uses <strong>UNet 3+</strong> as its underlying neural network backbone. Unlike standard U-Net (which only connects equivalent encoder-decoder scales), UNet 3+ incorporates <strong>full-scale skip connections</strong> that combine low-level spatial details with high-level semantic features across all 5 feature scales simultaneously, providing precise localization across varied cell sizes [9].</p><h4>2. Self-Supervised Learning (SSL) without Ground-Truth</h4><p>Manual pixel-level annotation in multi-channel spatial transcriptomics is practically impossible [9]. BIDCell bypasses the need for annotated training masks by using a <strong>self-supervised learning (SSL)</strong> paradigm [9]. It automatically derives supervisory signals during training by balancing six synergistic, biologically-informed loss functions [9].</p><ol><li><strong>Nuclei Encapsulation Loss</strong>: Incentivizes predicted cell masks to completely enclose the pixels of their corresponding nucleus [9].</li><li><strong>Cell-Calling Loss</strong>: Expands boundaries outward from nuclei using data-driven shapes. It incorporates nuclear eccentricity to predict elongated morphologies for specific cell types (like fibroblasts) while maintaining compact shapes for others [9].</li><li><strong>Overlap Loss</strong>: Penalizes predictions where multiple cell instances attempt to claim the same pixel in crowded regions [9].</li><li><strong>Over-Segmentation Loss</strong>: Penalizes fragmented or broken cell predictions to maintain spatial mask cohesion [9].</li><li><strong>Positive &amp; Negative Marker Losses</strong>: Pulls marker gene signatures from public single-cell sequencing atlases (such as the Human Cell Atlas). It rewards cell masks that encapsulate positive cell-type markers and penalizes masks that capture negative markers from adjacent cell types. [9]</li></ol><h4><strong>3. Performance Metrics</strong></h4><p>By enforcing expression purity during segmentation, BIDCell significantly reduces cross-cell transcript contamination in dense tissue regions while capturing realistic cellular morphologies across major spatial platforms.</p><h3>Approach 3: Radical Alternative — Segmentation-Free Methods (FICTURE)</h3><p>A growing movement in spatial transcriptomics asks a provocative question: <strong>Why force continuous biological tissues into artificial cell boundary polygons at all?</strong></p><p>Traditional instance segmentation relies on nuclear stains that often discard <strong>50% to over 90% of captured transcripts</strong> because molecules reside in unlit cytoplasm, extracellular matrix, or non-nucleated cell structures. Segmentation-free methods bypass polygon masks entirely, replacing instance boundaries with <strong>subcellular semantic domain mapping</strong>.</p><h4>1. Submicron Factor Analysis (FICTURE)</h4><p>Rather than partitioning molecules into isolated cell containers, <strong>FICTURE</strong> (Si et al., 2024) models tissue expression as a continuous mixture of latent biological factors (representing cell types or microenvironments) [10].</p><ul><li><strong>Spatial Factorization: </strong>FICTURE fits spatial Latent Dirichlet Allocation (LDA) across a lattice of local anchor points, assigning every submicron pixel a probability vector across biological factors [10].</li><li><strong>Linear Scalability <em>(O(N))</em>:</strong> unlike older point-process models that scale quadratically, FICTURE processes spatial patches via stochastic variational inference, achieving linear runtime scaling <em>(O(N)) </em>within a lightweight, fixed memory footprint under 10 GB [10].</li></ul><h4>2. Recovering Complex Morphologies</h4><p>By evaluating every pixel rather than relying on DAPI nuclear seeds, FICTURE recovers critical cell populations that traditional segmentation systematically misses [10]:</p><ul><li><strong>Lipid-Laden Adipocytes:</strong> Fat cells where cytoplasm is distended around massive lipid droplets (i.e. fat cells) [10].</li><li><strong>Multinucleated Myofibers:</strong> Elongated muscle fibers that nuclear segmentation incorrectly fragments into spherical blobs [10].</li><li><strong>Vascular Architecture:</strong> Blood vessel walls and non-nucleated cells where traditional masks discard up to 94% of transcripts [10].</li></ul><h4>3. The Trade-Off</h4><ul><li><strong>Advantage: </strong>Evaluates 100% of spatial transcriptomics; completely immune to under-segmentation, over-segmentation, and transcript misassignment artifacts [10].</li><li><strong>Limitation: </strong>It cannot calculate single-cell physical metrics (such as exact cell volume or area).</li></ul><h3>My Hot Take</h3><p>To overcome the cell segmentation crisis and realize the full potential of high-resolution spatial transcriptomics, I believe that we need to embrace three key paradigm shifts:</p><h4>1. Stop Looking for a “Universal Winner”</h4><p>The benchmarks show that no single segmentation method universally excels across all metrics or tissue types. Pure vision models give us rich transcripts per cell but sacrifice coverage; multimodal models like BIDCell achieve high expression purity; and factor models like FICTURE excel at recovering unsegmentable morphologies. We should stop looking for one single tool to rule them all and start choosing segmentation strategies tailored explicitly to the biological question at hand.</p><h4>2. Embrace Multimodal Co-Inference</h4><p>I’m convinced the future of cell segmentation lies in models that refuse to evaluate optical images or RNA point clouds in isolation. By fusing 2D optical staining with spatial RNA point clouds and single-cell RNA sequencing (scRNA-seq) reference atlases, models like BIDCell give us the best of both worlds: realistic cell shapes and pure, unpolluted transcript profiles.</p><h4>3. Mandate Standardized Benchmarking</h4><p>Finally, I believe our community must integrate standardized, reproducible benchmarking workflows — such as unified Nextflow pipelines paired with multi-metric evaluation suites — to rigorously quantify segmentation error and transcript purity before publishing reference atlases or training foundation models [1].</p><h4>Sources</h4><ol><li><a href="https://www.nature.com/articles/s41592-026-03272-x">Xavier M., Sumeer A., et al: <em>Benchmarking segmentation methods for spatial transcriptomics </em>(23 Oct, 2026)</a></li><li><a href="https://people.cmm.minesparis.psl.eu/users/marcoteg/cv/publi_pdf/MM_refs/vincent/1991_PAMI_VincentSoille_watershed.pdf">Vincent L, Soille P. (1991) <em>Watersheds in digital spaces: an efficient algorithm based on immersion simulations.</em></a></li><li><a href="http://web-ext.u-aizu.ac.jp/course/bmclass/documents/otsu1979.pdf">Otsu N. <em>A threshold selection method from gray-level histograms.</em> IEEE Trans Syst Man Cybern. 1979</a></li><li><a href="https://www.youtube.com/watch?v=KuXjwB4LzSA">3 Blue 1 Brown: <em>But What Is A Convolution?</em></a></li><li><a href="https://arxiv.org/pdf/1505.04597">Olaf R., Philipp Fischer, et al: <em>U-Net: Convolutional Networks for Biomedical Image Segmentation</em></a></li><li><a href="https://www.biorxiv.org/content/10.1101/2020.02.02.931238v1.full">Carsen S., Michalis M., et al: <em>Cellpose: a generalist algorithm for cell segmentation</em></a></li><li><a href="https://arxiv.org/pdf/2606.09675">Ishaque et Al. (2026): <em>The Challenge of Cell Segmentation in Spatially Resolved Transcriptomics</em></a></li><li><a href="https://www.biorxiv.org/content/10.1101/2020.10.05.326777v1.full.pdf">Viktor Petukhov et al. <em>Bayesian Segmentation of Spatially Resolved Transcriptomics Data</em></a></li><li><a href="https://www.nature.com/articles/s41467-023-44560-w">Xiaohang Fu et al. (2024) <em>Biologically-informed self-supervised learning for segmentation of subcellular spatial transcriptomics data</em></a></li><li><a href="https://www.biorxiv.org/content/10.1101/2023.11.04.565621v2.full">Yichen Si et al (2023) <em>FICTURE: Scalable segmentation-free analysis of submicron resolution spatial transcriptomics</em></a></li></ol><h3>Bio</h3><p>I’m Ariel Mutebi, a full-stack web developer who has spent the last five of the seventeen years of his life staring at highlighted syntax on an off-black background. My passion for design runs deep — when I was a kid, I wanted to be an aerodynamicist at Porsche. Now, I view web design as a functional art medium, and I’m always looking for ways to streamline my code bases, even if it means a 1000-line refactor. I’m currently studying all the sciences (physics, chemistry, biology, and math) at Cambridge A-levels, and I enjoy the rare privilege of being a TKS innovator.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=032972b3dda3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Digital genetic cartography: the nascent space of spatial transcriptomics software]]></title>
            <link>https://medium.com/@arielmutebi/digital-genetic-cartography-the-nascent-space-of-spatial-transcriptomics-software-273c9852876f?source=rss-61fa688d1dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/273c9852876f</guid>
            <category><![CDATA[spatial-transcriptomics]]></category>
            <category><![CDATA[the-knowledge-society]]></category>
            <dc:creator><![CDATA[Ariel Robert Mutebi]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 14:05:22 GMT</pubDate>
            <atom:updated>2026-10-19T13:48:51.689Z</atom:updated>
            <content:encoded><![CDATA[<p>With the dawn of the twenty-first century, the world welcomed the first working draft of the human genome. Funded by the U.S. government, and accelerated by cooperation with competitors, the human genome project had sequenced over three billion base pairs, that is, about 90% of our DNA. On June 26 2000, President Bill Clinton pronounced it, “The most wondrous map ever produced by humankind.” [<a href="https://clintonwhitehouse5.archives.gov/WH/New/html/genome-20000626.html">1</a>]</p><p>Since then, the field of genomics has been racing forward, leaving behind the first-generation sequencing methods for next-generation sequencing techniques like bulk RNA-seq, which enables analysis of gene expression in a tissue. Single-Cell RNA sequencing (scRNA-seq) followed, allowing gene expression to be analysed on a cell-by-cell basis. This step-up in resolution was significant because cells in a tissue often express genes differently, and data about those differences was lost in bulk-RNA seq. But even scRNA-seq was not enough, because information about the position of the cells which were expressing those particular genes was lost. To solve this, we arrive at the bleeding edge of spatial transcriptomics.</p><p>This article attempts to give a clear overview of the state of the technique, as well as investigate the current bottlenecks in the field.</p><h3>The Spatial Paradigm Shift: From Molecular Smoothies to Tissue Atlases</h3><p>A common analogy in structural biology compares bulk RNA-seq to a fruit smoothie. It gives you a taste all the flavors (gene expressions), but it is homogenised so that you can’t quite tell which flavour was from which fruit. Single-Cell RNA-seq upgrades this to a fruit salad, where you can tell which fruit in particular you’re tasting. But you lose context of the place from which the fruit was sourced.</p><p>Spatial transcriptomics (ST), named in <em>Nature Methods</em> of the year in 2020, takes you back to the farm from which the fruit was harvested [<a href="https://www.nature.com/collections/dfibfggefc">2</a>]. It allows researchers to quantify gene expression while preserving the precise two- and three-dimensional of RNA molecules within tissue samples.</p><p>In biological systems, location is fate. Cells do not exist in isolation: they reside in intricate, highly-structured micro-environments governed by morphogen gradients, extracellular matrix mechanics, and continuous cell-to-cell signalling cascades. However, as hardware innovations — ranging from high-density barcoded arrays to multi-plexed florescence microscopy — have made spatial data acquisition routinely possible, a stark reality has emerged: the rate-limiting factor in spatial biology has shifted from the wet- to the dry-lab, from the data-collection to its processing.</p><h3>The Dual Landscape: Sequencing-Based vs Imaging-Based Platforms</h3><h4>1. Sequencing-Based Spatial Transcriptomics (sST)</h4><p>Platforms such as 10x Genomics Visium, Slide-seqV2, DBiT-seq, and Stereo-seq rely on solid-phase capture arrays covered with spatially barcoded oligonucleotides. An oligonucleotide is a manufactured sequence of DNA or RNA bases, and the barcode is the unique section of an oligonucleotide. The position of each oligonucleotide is predetermined on the capture array.</p><p>When a tissue sample is placed onto the slide, it is permeabilised so that its cell membranes become more permeable, letting poly-adenylated mRNA diffuse out of the cell and onto the surface below it. Poly-adenylated means that the mRNA has a long segment of adenine bases at its tail (which is the case for most mature mRNA molecules), and the oligonucleotide is fitted with a long segment of thymine bases to its tail. Adenine and thymine are complementary bases, so the mRNA forms hydrogen bonds with the local barcoded oligonucleotides.</p><p>The enzyme reverse transcriptase is added to the slide. This enzyme reads the mRNA <em>a</em>nd<em> </em>the barcode and synthesizes a complementary DNA strand. The cDNA is is then harvested and sequenced using Next-Generation Sequencing techniques.</p><p>The strength of sST is in achieving trancriptome-wide coverage. You do not need to decide beforehand which gene’s expression you want to analyse.</p><p>However, the trade-off is that significant computational resources must be spent on deconvolution. The capture arrays have limited, “spot-based” resolution. For example, Visium spots are are 55µm in diameter, capturing anywhere from 1 to over 50 cells per spot. Deconvolution therefore has to do with estimating the contribution of different cell types to the observed expression profile of a spot.</p><ul><li><strong>Data footprint</strong>: sST produces a high-dimensional gene × spatial-barcode count matrix, which is typically paired with a high-resolution histology image (e.g., H&amp;E or immunofluorescence).</li></ul><h4>2. Imaging-Based Spatial Transcriptomics (In Sutu Hybridization &amp; Sequencing)</h4><p>Platforms such as MERFISH (Vizgen MERSCOPE), 10x Genomics Xenium, CosMx SMI (Bruker/Nanostring), and seqFISH+ skip NGS altogether. Instead, they utilise iterative rounds of fluorescent in-situ hybridisation (FISH) or in-sutu sequencing directly within intact tissue, imaged via automated high-resolution microscopy.</p><p>The advantage of these platforms is that they offer subcellular resolution, locating individual RNA molecules with nanometer precision. However, they are constrained to pre-selected target gene panels, and they generate staggering file sizes that immediately overwhelm conventional workflows.</p><ul><li><strong>Data footprint</strong>: Point clouds consisting of millions to billions of individual RNA molecule detections, each defined by exact spatial coordinates (X, Y, Z), optical quality scores, and transcript identity, layered on top of multi-channel z-stack microscopy images.</li></ul><h3>Bottleneck 1: Data Infrastructure, Memory Scaling, and File formats</h3><p>The sheer volume of data generated by modern spatial platforms has exposed the inadequacies of standard bioinformatics data structures. In scRNA-seq, the data structure is a matrix of count values (Genes × Count), typically accommodated in-memory using object structures like AnnData in Python or SeuratObject in R. A typical scRNA-seq experiment involving 50,000 cells easily fits into a regular laptop’s RAM.</p><p>In contrast, a single imaging-based spatial experiment regularly outputs:</p><ul><li>Multi-channel, multi-terabyte raw TIFF or OME-TIFF image stacks</li><li>Millions of segmented polygon geometries</li><li>Tens to hundreds of millions of individual transcript X, Y, Z coordinates</li></ul><p>Attempting to load such datasets into system RAM causes instantaneous memory overflow. To break this bottleneck, the software ecosystem has been transitioning to out-of-core computational frameworks and chunked multi-scale data containers.</p><ol><li>SpatialData (scverse ecosystem): Built for Python, SpatialDataunifies spatial images, labels (segmentations), points (transcripts), and shapes (polygons) into a unified computational object. It leverages Zarr for lazy-loaded array storage, Dask for parallelized out-of-core computation, and GeoPandas for spatial geometries, allowing researchers to analyze multi-million cell datasets without holding the entire raw payload in active RAM.</li><li>SpatialExperiment &amp; Giotto (R/Bioconductor ecosystem): In R, SpatialExperiment extends the SingleCellExperiment class to incorporate spatial coordinates and image metadata, while frameworks like Giotto employ disk-backed structures to manage multi-layer spatial graphs.</li></ol><p>Despite these advances, <strong>interoperability remains a major sticking point</strong>. Converting complex spatial objects seamlessly between Python and R without dropping spatial coordinate systems, transformation matrices, or cell polygon representations remains a major headache for developers.</p><h3>Bottleneck 2: Upstream Image Processing and the Cell Segmentation Crisis</h3><p>For imaging-based spatial transcriptomics, the first computational step after image acquisition is cell segmentation — identifying the exact boundaries of individual cells in 2D or 3D space so that individual RNA transcripts can be correctly assigned to specific cells.</p><p>Cell segmentation is currently one of the most critical and problematic bottlenecks in the entire spatial pipeline.</p><h4>The failure modes of current segmentation algorithms</h4><p>Historically, cell segmentation relied on staining the nucleus with fluorescent dyes such as DAPI which bind strongly to DNA. Then, simple intensity thresholding would be applied to the image: spots which are brighter than the intensity threshold are taken to be the nuclei of the cells.</p><figure><img alt="Intensity thresholding" src="https://cdn-images-1.medium.com/max/1024/1*IglOK7y2RCBfiCDrrQgFBA.jpeg" /><figcaption>Intensity thresholding</figcaption></figure><p>However, nuclei only account for a fraction of the total cell volume, and many transcripts reside in the cytoplasm. To bridge this gap, modern pipelines deploy deep learning-based segmentation algorithms, including CellPose, StarDist, and Mesmer (DeepCell). While these models perform admirably on isolated cells in clean culture dishes, they routinely struggle in real-world human tissue sections characterized by:</p><ul><li><strong>High cell density and overlap:</strong> in dense tissues like tumour-infiltrating lymphocytes, lymphoid tissue, or brain gray matter, cell membranes press tightly against one another, making individual cell boundaries ambiguous.</li><li><strong>Morphological heterogeneity: </strong>a single tissue section can contain tiny, round lymphocytes alongside elongated, branching neurons or stromal fibroblasts. Uniform deep-learning segmentation models trained on specific cell morphologies often fail when encountering heterogenous cell types in the same field of view.</li><li><strong>Staining Artifacts and Tissue Thickness:</strong> flourescent signal attenuation, non-specific background auto-flourescence, and folds in the slice of tissue under inspection frequently create false membrane boundaries.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Z65rEkafmTEnc-YJV7rVw.jpeg" /><figcaption>Transcript spillover caused by cell segmentation errors</figcaption></figure><h4>The Transcript Misattribution Problem</h4><p>When segmentation algorithms fail, the downstream consequences are catastrophic. As illustrated in the diagram above, if a segmentation boundary is shifted by a few micrometers, RNA transcripts expressed highly by a tumour cell can be falsely assigned to an adjacent infiltrating T-cell. This <strong>transcript spillover</strong><em> </em>or <strong>leakage</strong> creates “phantom cell states” — falsely leading researchers to conclude that cytotoxic T-cells are expressing epitheleal tumour markers.</p><p>To mitigate this, software developer are working on cell-segmentation-free methods (such as Baysor or Spatially-Aware Point-Process models), which cluster RNA transcript coordinate points directly based on spatial density and transcript co-occurence, drawing cell boundaries <em>after</em> observing the mRNA distribution rather than relying solely on imperfect images.</p><h3>Bottleneck 3: Spot Deconvolution and Spatial Domain Identification</h3><p>Once spatial transcriptomics data has been processed, researchers face two related challenges: determining which cell types contributed to each measurement and identifying the larger tissue regions those cells form.</p><h4>1. Spot Deconvolution</h4><p>In sequencing-based platforms such as 10x Visium, a single spot may capture gene expression from multiple cells. Computational <strong>deconvolution</strong> attempts to estimate the relative contributions of different cell types to this mixed signal.</p><p>Tools such as <a href="https://www.nature.com/articles/s41587-021-00830-w">RCTD</a> and <a href="https://www.nature.com/articles/s41587-021-01139-4">Cell2location</a> use reference datasets, typically derived from single-cell RNA sequencing, to help identify these contributions. However, their accuracy depends partly on the quality and completeness of the reference. Missing cell types and highly similar gene-expression profiles can make populations difficult to distinguish, leading to uncertain or inaccurate estimates.</p><h4>2. Spatial Domain Identification (Spatial Clustering)</h4><p>Researchers also need to identify meaningful tissue regions, such as tumour boundaries, immune-rich areas, or distinct layers of the brain. This is known as <strong>spatial domain identification</strong>, or spatial clustering.</p><p>Conventional clustering based on gene-expression similarity can group biologically similar cells from distant locations or produce fragmented regions when measurements are noisy. Spatial methods address this by considering physical proximity alongside gene expression, helping identify coherent tissue structures.</p><p>The main challenge is balancing spatial consistency with biological detail. Too little spatial constraint can leave noisy, fragmented maps; too much can blur genuine boundaries or obscure narrow structures. A visually smooth map is not necessarily a biologically accurate one.</p><h3>Bottleneck 4: Multi-Sample Alignment, Batch Effects, and 3D Tissue Reconstruction</h3><p>Spatial transcriptomics typically begins with measurements from individual tissue sections. However, understanding how biological structures vary between between patients or across an organ requires researchers to compare and combine multiple datasets. This introduces two related computational challenges: correcting technical differences between samples and aligning tissue sections to reconstruct their three-dimensional organisation.</p><h4>The Spatial Batch Correction Dilemma</h4><p>Measurements from different experiments can very because of differences in tissue preparation, staining, sequencing technologies or laboratory protocols. These unwanted technical differences are known as <strong>batch effects</strong>. Software tools such as <a href="https://www.nature.com/articles/s41467-023-35947-w">PRECAST</a> try to reduce these effects without removing genuine biological differences.</p><h4>Reconstructing Three-Dimensional Tissue</h4><p>Most spatial transcriptomics datasets capture thin, two-dimensional tissue sections. Reconstructing a three-dimensional tissue atlas requires aligning consecutive slices despite distortions introduced during cutting, mounting, and staining. Registration tools such as <a href="https://www.nature.com/articles/s41592-022-01459-6">PASTE</a> and <a href="https://www.nature.com/articles/s41467-023-43915-7">STalign</a> estimate these alignments using spatial and, depending on the method, molecular or image information. However, tissue between measured sections remains unobserved, so the reconstructed volume cannot fully establish structures in those gaps.</p><h3>Bottleneck 5: Spatial Statistics and Cell–Cell Communication</h3><p>Once tissue regions and cell types have been identified, researchers can investigate how gene expression varies across the tissue and how cells may communicate with one another. Both tasks require statistical methods that account for spatial context, but each presents distinct challenges.</p><h4>Spatially Variable Gene Detection</h4><p>Researchers want to identify spatially variable genes (SVGs) — genes whose expression patterns change systematically across physical space. Studying SVGs can reveal tissue layers, localised activity, or gradients associated with development and disease.</p><p>Methods such as <a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC6350895/">SpatialDE</a> and <a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC8218388/">SPARK-X</a> attempt to use statistical approaches to distinguish spatial patterns from random variation. But performance varies with dataset size, gene-expression patterns, and the statistical assumptions of each method. Some approaches become computationally expensive on large datasets, while different methods can produce substantially different lists of significant genes. A <a href="https://link.springer.com/article/10.1186/s13059-023-03145-y">2024 benchmark</a> found discrepancies between methods in their selected genes, statistical reliability, and computational requirements.</p><h4>Inferring Cell-Cell Communication</h4><p>Cells influence one another through signaling molecules known as ligands. A ligand produced by one cell may bind to a receptor on another, influencing the internal activities of the internal cell via a signaling cascade.</p><p>Software uses gene-expression data and known ligand-receptor relationships to infer potential communication between cell types. The limitation is that gene expression alone does not establish that signaling actually occurs. Cells may express a compatible ligand and receptor yet be too far apart to interact. Spatial data helps narrow the possibilities by incorporating physical proximity and shared tissue microenvironments. Tools like <a href="https://www.nature.com/articles/s41592-022-01728-4">COMMOT</a> and <a href="https://www.nature.com/articles/s41596-024-01137-1">CellPhoneDB v5</a> incorporate spatial information into communication analysis differently.</p><p>A remaining challenge is accounting for physical barriers to signaling, such as basement membranes and collagen-rich extracellular matrix.</p><h3>Bottleneck 6: Visual Analytics, Interactivity, and the User Experience Gap</h3><p>Spatial transcriptomics produces data that researchers need to explore visually: microscopy images, individual RNA transcripts, cell boundaries, gene-expression patterns, and spatial clusters. Bringing these layers together in an interactive viewer is challenging when a single experiment can contain millions of data points alongside gigapixel-scale images.</p><p>Loading and rendering everything at once can overwhelm a browser’s memory and processing capacity. Tools such as <a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC10149187/">TissUUmaps</a> and <a href="https://www.nature.com/articles/s41592-024-02436-x">Vitessce</a> address this through scalable visualization approaches, including multiresolution image viewing, GPU-accelerated rendering, and coordinated views of different data modalities.</p><p>However, visualization involves more than rendering performance. Researchers need to move between tissue morphology, individual cells, gene expression, and computational results without losing spatial context. They also need tools that fit different workflows: code-based environments offer flexibility, while graphical interfaces can make exploration more accessible to researchers who do not program.</p><p>These requirements create competing demands. Simplifying or downsampling data can improve responsiveness but may hide rare spatial patterns; displaying more detail increases computational demands. Integrating multiple data formats and analysis workflows adds further complexity.</p><p>The challenge is to build tools that make large spatial datasets <strong>fast to explore, easy to interpret, and accessible to researchers with different technical backgrounds</strong>, without sacrificing biologically important detail.</p><h3>A Fragmented but Converging Software Ecosystem</h3><p>No single software package handles every stage of spatial transcriptomics equally well. Instead, researchers assemble workflows from tools with different specializations. Seurat and <a href="https://www.nature.com/articles/s41592-021-01358-2">Squidpy</a> provide spatial analysis within established R and Python ecosystems, while <a href="https://www.nature.com/articles/s41592-024-02212-x">SpatialData</a> addresses the challenge of representing and coordinating heterogeneous spatial data. Other tools target specific bottlenecks: <a href="https://www.nature.com/articles/s41587-021-01044-w">Baysor</a> helps assign transcripts to cells without relying entirely on image-based segmentation, <a href="https://www.nature.com/articles/s41467-023-43915-7">STalign</a> aligns spatial datasets across sections and samples, and <a href="https://www.nature.com/articles/s41592-024-02436-x">Vitessce</a> enables interactive exploration of large, multimodal datasets.</p><p>This specialization reflects the complexity of the underlying problem, but it also creates integration challenges. Researchers must jump between data formats, coordinate systems, analytical methods, and visualization environments without losing information or reproducibility. The next stage of spatial transcriptomics software development will depend not only on better individual algorithms, but also on making these components work together reliably.</p><h3>Conclusion: Cartography for the Next Century of Biology</h3><p>When President Bill Clinton celebrated the completion of the Human Genome Project in the summer of 2000, he praised a one-dimensional map — a linear reference sequence of three billion chemical letters. Its was a foundational triumph, but it was equivalent to having an index of every street name in the world without knowing which city or continent they belonged to.</p><p>Spatial transcriptomics provides the missing coordinate system. By weaving molecular genetics directly into the structural, physical architecture of living tissue, it gives humanity its first true multi-dimensional digital atlas of biology.</p><p>Yet, as this article has explored, the biological hardware has temporarily outpaced the software infrastructure. The journey from raw fluorescent photons and spatially-barcoded sequencing reads to meaningful biological discovery is currently impeded by significant computational bottlenecks: memory-bound file formats, imprecise deep-learning cell segmentations, reference-dependent deconvolution models, 3D modelling inconsistencies, and high-complexity spatial statistics algorithms.</p><p>Overcoming these bottlenecks will require a massive, multi-disciplinary effort. Computer scientists, software engineers, bioinformaticians, pathologists, and tissue biologists must collaborate to build standardized, open-source out-of-core computing frameworks, scalable spatial statistics, and intuitive visual exploration engines.</p><p>I believe that when these software bottlenecks are finally broken, spatial transcriptomics will transition from an expensive specialized research technique into a routine clinical diagnostic tool — unlocking a new era of precision medicine for the human race.</p><h4>Bio</h4><p>I’m Ariel Mutebi, a full-stack web developer who has spent the last five of the seventeen years of his life staring at highlighted syntax on an off-black background. My passion for design runs deep — when I was a kid, I wanted to be an aerodynamicist at Porsche. Now, I view web design as a functional art medium, and I’m always looking for ways to streamline my code bases, even if it means a 1000-line refactor. I’m currently studying all the sciences (physics, chemistry, biology, and maths) at Cambridge A-levels, and I enjoy the rare privilege of being a TKS innovator.</p><h4>Citations</h4><ol><li><a href="https://clintonwhitehouse5.archives.gov/WH/New/html/genome-20000626.html">https://clintonwhitehouse5.archives.gov/WH/New/html/genome-20000626.html</a></li><li><a href="https://www.nature.com/collections/dfibfggefc">https://www.nature.com/collections/dfibfggefc</a></li></ol><ul><li><strong>Ecosystems:</strong> Squidpy (Palla et al., <em>Nat Methods</em> 2022), Giotto (Dries et al., <em>Genome Biol</em> 2021) and SpatialExperiment (Righelli et al., <em>Bioinformatics</em> 2022).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=273c9852876f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>