A self-supervised foundation model for robust and generalizable representation learning in STED microscopy

A self-supervised foundation model for robust and generalizable representation learning in STED microscopy

The procedure for the preparation of primary dissociated rat neuronal cultures and acute mouse brain slices complied with the ethics regulation of the animal care committee of Université Laval.

DatasetsSelf-supervised pretraining datasets

The STED-FM dataset42 consisted of 37,387 images of varying size which were split into 224 × 224 crops. The resulting size of the dataset was 976,022 crops, all of which were used for pretraining STED-FM. Within the STED-FM dataset, the protein of interest is known in 238,683 crops. In total, 24 different proteins were identified in this subset, and the total number of crops per protein is reported in Supplementary Table 12.

We benchmarked STED-FM against pretraining of ViT-S on four other datasets which cover the natural image, microscopy and super-resolution microscopy domains. In order of similarity to the STED image domain: SIM14, HPA44, a subset of the JUMP-CP dataset (JUMP24) and ImageNet-1k6. For ImageNet, we did not re-train our own ViT-S model on the ImageNet-1k dataset, but used the pretrained weights available from the PyTorch Image Models library92.

For SIM, we used all the reconstructed images from the datasets used in ref. 14. The dataset is aggregated from the 3D-RCAN dataset93, the BioSR dataset94, DeepBacs dataset95 and the EMTB dataset96.

In the case of HPA, we treated the four channels of an image as four independent images. We performed random cropping to sample 224 × 224 crops from the 512 × 512 original images during training.

For JUMP, we used the JUMP Cell Painting datasets24, available from the Cell Painting Gallery97 on the Registry of Open Data on AWS. We sampled 3.7 million images from the different cpg-0016 subfolders. As images were of variable sizes, we performed random cropping of the images during training to obtain crops of size 224 × 224.

Each image in the dataset was normalized to the [0, 1] range using min–max values (JUMP and HPA), or the 0.001 and 0.999 quantile (STED-FM dataset and SIM). The number of independent images and the number of crops for each dataset can be found in Supplementary Table 1.

Size-matched datasets

We trained ViT-S on HPA and JUMP with a dataset size equal to that of STED-FM. This downsamples JUMP from 3.7 million images and HPA from 1.1 million images to 976,022, exactly (the size of STED-FM’s pretraining dataset). Images were selected randomly. We did not alter the pretraining of ImageNet, as we use the publicly available weights from torchvision98. We also elected not to downsample every dataset to the SIM dataset size of 205,946 considering that the first downsampling step had already altered considerably the performance of the JUMP pretraining.

Supervised downstream datasets

For the different downstream experiments performed, we used a total of 20 super-resolution microscopy datasets and 7 confocal microscopy datasets.

Classification

We used nine downstream classification datasets: two ID-STED, two OOD-STED and five OOD-MIC (Supplementary Table 3).

STED optimization (SO; ID-STED): dataset of STED microscopy images from50 containing four different structures: the cytoskeleton proteins F-actin and tubulin, the calcium-dependent protein kinase II (CaMKII), and the post-synaptic protein PSD95. Only the images with an image quality above 0.7 were used. The quality rating was obtained by a manual expert annotation in ref. 50. The train and test splits from the original publication were used. A validation dataset was created by sampling 10% of the training images from each class. The downstream task consisted in classifying the four aforementioned structures (Extended Data Fig. 1).

Neural activity states (NAS; ID-STED): STED microscopy dataset of PSD95 imaged under four different experimental conditions from45. It highlights activity-dependent remodeling of PSD95 following different stimulations: High Mg2+/Low Ca2+ (low activity), 0Mg2+/Gly/Bic (chemically induced long-term potentiation), glutamate/glycine (chemically induced long-term depression) and tetrodotoxin (upscaling). The dataset was split into train (70%), validation (15%) and test (15%) sets. The downstream task consisted in classifying the four experimental conditions: low activity, chemically induced long-term potentiation, chemically induced long-term depression and upscaling (Extended Data Fig. 1).

Peroxisome (Px; OOD-STED): STED microscopy dataset of images containing peroxisome organelles from ref. 51. It contains images of yeast cells grown for four different time periods in a medium containing 0.5% methanol: 4 h methanol, 6 h methanol, 8 h methanol and 16 h methanol. The dataset was acquired in triplicate. We combined two replicates for training and validation, with a random split of 80%:20%, respectively. The third replicate was used for testing. The downstream task consisted in classifying the four time periods (Extended Data Fig. 1). Images were padded with zeros to match the required image size of 224 × 224 pixels.

Polymer rings (PR; OOD-STED): STED microscopy images from ref. 52 showing two proteins which self-assemble into filamentous polymers and which are part of the cell division (Cdv) system: CdvB1 and CdvB2. We randomly split the dataset into training, validation and testing (70%, 15% and 15%, respectively). The downstream task consisted in classifying CdvB1 versus CdvB2 (Extended Data Fig. 1). Images were padded with zeros to match the required image size of 224 × 224 pixels.

DL-SIM (OOD-MIC): SIM images of four different subcellular structures obtained from ref. 99: microtubules, adhesions, mitochondria and F-actin. We used the high-quality reconstructed SIM images and the training and testing dataset splits from the original publication. We subsampled 30% of the training dataset to obtain a validation dataset. The downstream task consisted in classifying the aforementioned structures (Extended Data Fig. 1).

BBBC026 (OOD-MIC): we used image set BBBC026v1 (ref. 100), available from the Broad Bioimage Benchmark Collection101. The classification task consisted in predicting the negative and positive controls. Images were randomly split into training, validation, and testing (70%, 15% and 15%, respectively). Crops of 224 × 224 pixels were extracted from the images without overlap for training.

BBBC052 (OOD-MIC): we used image set BBBC052v1 (ref. 102), available from the Broad Bioimage Benchmark Collection101. This dataset was acquired on a confocal microscope. The downstream task was a four-class classification task: CK-666/KD, Cofilin1KD/KD, PFN1KO/KO, TBeta4KD/KD. Images were randomly split into training, validation and testing (70%, 15% and 15%, respectively). Crops of 224 × 224 pixels were extracted from the images without overlap for training.

BBBC053 (OOD-MIC): we used image set BBBC053v1 (ref. 102), available from the Broad Bioimage Benchmark Collection101. This dataset was acquired on a confocal microscope. The downstream task consisted in classification of images of mitochondria treated with either dimethylsulfoxide or carbonyl cyanide m-chlorophenyl hydrazone to induce and detect changes in mitochondrial morphology. Images were randomly split into training, validation and testing (70%, 15% and 15%, respectively). Crops of 224 × 224 pixels were extracted from the images without overlap for training.

HPA classification (OOD-MIC): we used the classification labels provided as part of the HPA Image Classification competition103. The downstream task was a multi-label, multi-class classification task with 28 possible labels. Images were randomly split into training, validation and testing (70%, 15% and 15%, respectively). We performed random cropping to sample 224 × 224 crops from the 512 × 512 original images during training. Only the green channel was used for this task. Following the evaluation procedure of the competition, we reported the F1-score as a performance metric instead of the classification accuracy.

Segmentation

We used six downstream segmentation datasets: two ID-STED, two OOD-STED and two OOD-MIC (Supplementary Table 4). Example images and ground-truth segmentations are shown in Supplementary Fig. 9.

F-actin (ID-STED): STED microscopy dataset of images containing two segmentation classes: F-actin rings and F-actin fibers from ref. 54. The training, validation, and test splits from the original publication were used. The downstream task consisted in segmenting regions containing F-actin rings and/or fibers (Extended Data Fig. 1). The ground-truth segmentation masks consist of polygonal bounding boxes around the structure of interest, making them weak labels.

Synaptic Protein Zoo (SPZ; ID-STED): STED microscopy dataset of PSD95 and Bassoon images from ref. 45 were annotated using the citizen science platform Zooniverse53. The ground truths are semantic segmentation masks obtained from the majority class defined from 10 annotations per synaptic nanocluster for each task (segmentation and classification). The segmentation masks correspond to the aggregation (pixel-wise) of all voted masks, defining a probability at every pixel. Not all synaptic proteins in the images have been annotated, resulting in weak labels. The classes correspond to nanocluster morphology: round, elongated, perforated and multi-domain proteins. The downstream task consisted in the semantic segmentation of the four nanocluster morphologies (Extended Data Fig. 1).

FP (OOD-STED): STED microscopy dataset of podocyte FPs from ref. 57. The ground-truth masks are two-channel segmentations of FP and slit diaphragm regions. We used the training and testing splits provided by the authors of the original publication. We subsampled 20% of the training set to obtain the validation dataset. The downstream task consisted in the semantic segmentation of FP and slit diaphragm regions (Extended Data Fig. 1).

Lioness (OOD-STED): STED microscopy dataset of structures and their boundaries acquired using the Lioness procedure from ref. 26. The four imaging volumes from the original publication were split into two volumes for training, one for validation and one for testing. The downstream task consisted in semantic segmentation of structures and their boundaries (Extended Data Fig. 1).

LCN (OOD-MIC): confocal image stacks of the LCN in cortical rat bone104. The downstream task consisted in a three-class segmentation of the canaliculi, lacunae and canals. We did not use all frames from the confocal stack to create the dataset splits, skipping every ten frames to simulate a small dataset. We split the dataset into training, validation, and testing splits at the stack level (70%, 15% and 15%, respectively) and extracted crops of 224 × 224 pixels.

DeepD3 (OOD-MIC): We used the dataset from DeepD3, an open deep learning-based framework to robustly quantify dendritic spines in microscopy data105. The downstream task consisted in a two-class segmentation of the dendrite and the spine. We used all frames from the dataset. We used the training split provided by the authors for the training and validation datasets (respectively 90% and 10%). The validation split provided by the authors was used for testing. We cropped all frames to 224 × 224 pixels without overlap, making sure that a crop contained more than 1% of foreground. The foreground was obtained by Otsu thresholding.

Denoising

We used four OOD-STED downstream denoising datasets (Supplementary Table 7). Example of pairs of low-SNR and high-SNR images are shown in Supplementary Figs. 17–19.

α-Tubulin (OOD-STED): we used the STED denoising dataset of α-tubulin dataset published previously106. During training we split the training dataset into training and validation (90% and 10%, respectively). We used the testing split provided by the authors. The images in the dataset were 256 × 256 pixels, we cropped the image to 224 × 224 pixels from the top-left corner. We registered the low-SNR image on the high-SNR version with translation using the SimpleITK library107.

β-Tubulin (OOD-STED): we used the STED dataset of β-tubulin provided in ref. 68. As in the original publication, low SNR frames were summed to generate the high SNR image. Before summing, low SNR images were registered to one another using a rigid body transformation. The StackReg plugin implemented in ImageJ was used for registration108. The images were cropped to 224 × 224 pixels. We kept 1,200 crops for training as in the original publication and used 100 crops for validation and 100 crops for testing.

VGAT-LQHQ (OOD-STED): we acquired pairs of low and high SNR STED images on our Abberior Infinity line microscope, a different microscope than the one used for the generation of the STED-FM dataset109. The vesicular GABA transporter (VGAT) was immunostained in fixed acute mouse brain slices. The low and high SNR STED image acquisition only differed in the number of accumulations: one accumulation for the low-SNR image and ten accumulations for the high-SNR STED. We registered the low-SNR image on the high SNR version with translation using the SimpleITK library107. Images were then cropped to 224 × 224 pixels for training.

Gephyrin (OOD-STED): we acquired pairs of low- and high-SNR STED images on our Abberior Infinity line microscope, a different microscope than the one used for the generation of the STED-FM dataset109. The synaptic protein gephyrin was immunostained in fixed acute mouse brain slices. The low- and high-SNR STED image acquisition only differed in the number of accumulations: one accumulation for the noisy image and ten accumulations for the high SNR STED. We registered the low-SNR image on the high-SNR version with translation using the SimpleITK library107. Images were then cropped to 224 × 224 pixels for training.

Super-resolution

We used two OOD-STED downstream super-resolution datasets (Supplementary Table 7)

VGAT-SR (OOD-STED): we acquired pairs of confocal and STED images on our Abberior Infinity line microscope, a different microscope than the one used for the generation of the STED-FM dataset110. The VGAT-SR dataset was acquired on the same samples as the VGAT-LQHQ dataset. The low-resolution images in this dataset correspond to the confocal images of the VGAT-LQHQ dataset. We registered the confocal image on the STED with translation using the SimpleITK library107. Images were then cropped to 224 × 224 pixels for training.

F-actin-SR (ID-STED): we used the publicly available dataset from ref. 69 containing pairs of confocal and STED images of the protein F-actin. We used the provided dataset splits for training, validation, and testing. The training and validation datasets are already provided as crops. For the testing dataset we extracted 224 × 224 pixels size crops from the image without overlap. We ensured that at least 10% of foreground was found within the image. For all crops, we normalized crops (confocal and STED) using a min–max normalization. For training Pix2Pix and the diffusion models in the low-data regime, we randomly subsampled images from the training dataset, ensuring that different models with the same seeds had the same images in their training sets. We kept the validation and test sets the same as in the full-data scenario.

Latent attribute manipulation

For the latent attribute manipulation experiments (including those from the ‘Pattern discovery’ section), we used variants of datasets introduced beforehand, as well as new ones. Each dataset was split into training, validation and test sets. The train and validation sets were used for training the SVM and obtaining the normal vector to the decision boundary. Afterwards, we sampled images from the test set to serve as anchors to the manipulation trajectories.

F-actin to tubulin dataset: to train the SVM, we sampled all F-actin and tubulin images from the SO dataset with image quality scores above 0.7 (ref. 50). This resulted in 1,101 images for training, 111 images for validation and 60 F-actin test images as anchors (Fig. 4d).

Image quality dataset: the ground truth quality scores (ranging from 0 to 1) for this dataset were obtained from the annotations of the original dataset in ref. 50. A small convolutional neural network was trained to assign a quality score to images of F-actin. We used this network to measure the quality of the generated images. Images with quality scores lower than 0.60 were assigned to the low-quality class, whereas those with scores higher than 0.70 belonged to the high-quality class. Images with scores between these thresholds were discarded to reduce the ambiguity near the SVM’s decision boundary. This resulted in 1,623 images for training, 147 for validation and 40 low-quality F-actin images as candidate anchors (Fig. 4e–g). We discarded anchors with a quality score lower than 0.2, as we found those to be too far OOD for the algorithm to work as desired. This resulted in 27 anchors used for the analysis.

Image resolution dataset: the image resolution dataset consisted of images of the presynaptic protein Bassoon (STAR635P) imaged using two different STED laser powers111. The high-resolution images were acquired with a STED depletion power of 67.7 mW and the low-resolution images with a depletion power of 22.4 mW. The resulting images had average resolutions of 86 nm (high resolution) and 117 nm (low resolution; Supplementary Fig. 41). The dataset consists of 97 training images, 23 validation images and 12 low-resolution image anchors (Fig. 4h–j). The image resolution was measured using the decorrelation analysis112.

Synaptic development dataset: the synaptic development dataset consisted of STED images of PSD95 from neuronal cortical cultures fixed at 12 and 25 days in vitro (DIV12 and DIV25)76. We used the DIV12 and DIV25 classes for the latent attribute manipulation. We filtered out images with low signal (foreground intensity <0.15 after min–max normalization). The final dataset resulted in 311 images for training, 144 images for validation and 62 images of the DIV12 class as anchors (Fig. 5a–e).

Activity-dependent F-actin dataset: we used the F-actin activity-dependent dataset provided in ref. 19 for training the SVM. For the latent attribute manipulation experiment (Fig. 5f,g) we used the images of DIV13 neurons treated with a high Mg2+/low Ca2+ solution (low activity) and a glutamate/glycine solution (high activity). For the quantification of the prevalence of compact assemblies in F-actin stained images, we used all images from DIV13 neurons provided in ref. 54 (Fig. 5f–i).

Image retrieval

For the quantification of the image retrieval experiments, we used a dataset of F-actin images (Fig. 2j).

F-actin conformations dataset: the F-actin conformations dataset consists of F-actin STED images from several rat hippocampal neuronal cultures fixed between DIV12 and DIV15 (79 images)55. Nanoclusters are defined as very dense small round F-actin aggregation (around 100 nm in diameter) along the dendritic shaft. Compact assemblies are large dense F-actin aggregations that are on the dendritic shaft. Spines are identified as protrusions that extend from the dendritic shaft.

Sample preparation and acquisition
VGAT-LQHQ, Gephyrin and VGAT-SR datasets

For STED imaging, super-resolution imaging was performed using an Abberior INFINITY STED microscope (Abberior Instruments). The system was equipped with a ×60 oil immersion objective lens (NA 1.42; Olympus UPLXAPO60XO), a motorized stage and adaptive optics with spherical aberration correction ranging from 0 to 0.30 during imaging. Wavelengths of 485 nm and 640 nm were used for the experiment. The system was equipped with a 775-nm depletion laser (40 MHz, 1.2-ns pulse duration; MPB Communications). All lasers were operated at 40 MHz. The emitted fluorescence photons were detected by avalanche photodiode detectors (APDs) through a pinhole set at approximately 0.81 Airy units. Emission from ATTO 490LS and STAR RED was collected using a tunable detection filter with a bandwidth of 650–755 nm. The acquired images were visualized and processed using Fiji software (ImageJ, v.1.54p).

For acute brain slices preparation, all animal procedures were conducted in accordance with the guidelines of the Animal Protection Committee of Université Laval. C57BL/6 mice (Charles River Laboratories) were killed by intracardiac perfusion. Male and female animals (aged 12–14 weeks) were first anesthetized via intraperitoneal injection of a 20% urethane solution. Residual blood was then washed out by intracardiac perfusion with ice-cold PBS, followed by perfusion with a hybrid fixative solution containing paraformaldehyde (PFA) and glyoxal, based on a solution described previously113 (4% PFA, 0.4% glyoxal and 0.1% methanol in PBS). Brains were collected and post-fixed in the same solution for 24 h. Tissue was then sectioned into 40-μm-thick slices using a vibratome. Finally, slices were cryopreserved at −20 ∘C in a cryopreservation solution until use. For the experiments, brain slices from male and female mice (50:50 ratio) were used.

For the staining procedure, brain slices were washed in PBS containing 0.1 M glycine, then permeabilized and blocked for 30 min in PBS (20 mM) containing 0.2% Triton X-100 and 2% normal goat serum. Slices were incubated overnight at 4 ∘C on a shaker with VGAT (Synaptic Systems, rabbit, cat. no. 131 003) diluted in blocking solution (1:500). The following day, slices were incubated for 2 h at room temperature on a shaker with goat anti-rabbit ATTO 490LS secondary antibody (Hypermol, cat. no. 2309-1MG) and a gephyrin antibody fluorescence-labeled with abberior STAR RED (Synaptic System, mouse, cat. no. 147 011AbRED) diluted in blocking solution (1:250 and 1:500, respectively). Slices were washed with PBS between immunostaining steps to wash out unbound antibodies. Finally, the slices were mounted in PVA with DABCO for imaging.

Synaptic development dataset

For STED imaging, super-resolution imaging was performed on an Abberior Expert-Line STED system (Abberior Instruments). This system was equipped with a ×100 oil immersion objective lens with a numerical aperture of 1.4 (Olympus, model UPLSAPO100XO), a motorized stage and an auto-focus unit. An excitation wavelength of 640 nm was used for the experiments. The system was equipped with a 775-nm depletion laser (40 MHz, 1.2-ns pulse duration; MPB Communications). All lasers were operated at 40 MHz. The emitted fluorescence photons were detected by APDs through a pinhole set at approximately 1 Airy unit. Far-red dyes were detected with a ET685/70 filter (Chroma). Images were acquired with a pixel size of 20 nm. The acquired images were visualized and processed using Fiji software (ImageJ, v.1.54p) or Python.

For the neuronal cell culture, extraction and culture of cortical neuronal cells was performed following the protocol described elsewhere114 and in accordance with the guidelines of the animal care committee of Université Laval. In brief, neuronal cultures from the cortex were obtained using neonatal Sprague–Dawley male and female rats. P0–P1 rats were killed by decapitation before dissection. Cells were dissociated using enzymatic digestion and mechanical dissociation, and then seeded onto 12-mm coverslips coated with poly-d-lysine and laminin (40,000 cells per coverslip). Neurons were cultivated in a growth medium composed of Neurobasal and B27 (in a 50:1 ratio), enriched with penicillin–streptomycin (25 U ml−1 and 25 μg ml−1) and 0.5 mM L-GlutaMAX (by Invitrogen). After 5 days, Ara-C (5 μM; from Sigma-Aldrich) was added into the medium to limit the proliferation of non-neuronal cells. Cultures were fed twice a week, by replacing ~50% of the growth medium with serum- and Ara-C-free medium.

For the sample preparation and staining procedures, neuronal cultures were fixed for 20 min in 4% PFA solution (PFA 4%, sucrose 4%, phosphate buffer 100 mM and Na-EGTA 2 mM). Permeabilization and blocking were carried out simultaneously with a solution of Triton X-100 and 2% goat serum in PBS 20 mM for 30 min. Primary and secondary antibodies were successively incubated for 2 h and 1 h, respectively. Incubation of antibodies was performed in the blocking solution at room temperature. Immunostained coverslips were mounted in PVA with DABCO for imaging. PSD95 was stained with Fluotag-X2 anti-PSD95 abberior STAR635P (NanoTag, cat. no. N3702, 1:500 dilution).

Deep neural network pretrainingVision transformers: masked autoencoders

The vision transformers (ViTs) were pretrained on microscopy datasets using the masked autoencoding procedure introduced in ref. 31. In Supplementary Fig. 1, we show the training of ViTs of different architecture sizes: tiny, small, base and large. In all cases, a patch size of 16 was used. We used the architectures provided in the PyTorch Image Models library92. According to the results obtained, we selected the ViT-S architecture for STED-FM as it offered the best overall performance. Given an input size of 224 × 224, this resulted in a sequence length of 196 for all models, excluding the class token. All models were trained for 1,000 epochs with a batch size of 1,024. We used the same training hyperparameters as in the seminal implementation of the masked autoencoder (MAE)31. We used the AdamW optimizer115 with a learning rate of 1.5 × 10−3, weight decay of 0.05 and decay rates β1 and β2 of 0.9 and 0.95, respectively. We used a cosine annealing scheduler with a period of 20 epochs. For the configuration of the MAE, we used a masking ratio of 0.75 and a fixed decoder embedding dimension of 512 for all models. After pretraining, the lightweight decoder of the MAE procedure was removed and the ViT encoder served as the vision foundation model.

Unsupervised analysisViT attention maps

To extract an attention map from the pretrained ViT-S, the self-attention of the class token from the six attention heads in each of the 12 transformer blocks was averaged, resulting in 12 attention maps. The global attention map of the model was obtained by summing these 12 maps. A 0.5 quantile threshold was applied to the sum and the thresholded attention map was then rescaled to input size. The global attention maps were overlaid on the input intensity image and shown to domain experts in a user study (Fig. 2a,b).

Ridge regression

We trained a ridge regression model using the scikit-learn library116 to predict the spatial resolution, or image quality, given the latent feature vector of an image (Fig. 2c). A ridge regression model was trained independently for each pretraining dataset. A value of α = 1 was used for the regularization term (l2-norm).

Recursive consensus clustering

We performed clustering on the deep feature space of STED-FM for the NAS dataset. We followed previous work46, which is a recursive version of the consensus clustering algorithm introduced in ref. 47.

Consensus

Consensus clustering is a method which performs n trials of a clustering algorithm. In each trial we sample a subset representing ratio P of the dataset. These n resampling trials were performed for C different clustering algorithms or variants of the same clustering algorithm (such as k-means with different values of k), such that the final number of trials is given by N = n × C. At the end of the trials, for every possible pair of elements, the number of times the pair clusters together is divided by the number of trials in which the two elements were both part of the sampled subset. This produces a consensus matrix M. For our experiment, we used n = 30, P = 0.8, and used the k-means clustering algorithm with values of k ranging from 2 to 10 (C = 8).

Recursion

We determined the best number of clusters for recursion by computing the consensus matrices for the different values of k. We calculated how close each matrix is to a perfect consensus matrix (one which would have all elements either 0 or 1). The selected k* value that produces a matrix closest to a perfect one was chosen as the optimal number of clusters. Recursion was then performed on those k* clusters.

Stopping

The recursion was performed until all recursion paths were completed. As proposed previously46, this happens when clustering returns an intracluster stability <0.80, or an intercluster overlap >0.20. Letting S be the set of pairs that cluster together and W be the set of pairs that do not, the intracluster stability and intercluster overlap were defined as:

$$\begin{array}{c}\mathrm{Intracluster}\,\mathrm{stability}=\frac{1}{| S| }\mathop\sum \limits_{(i,j)\in S}{M}_{i,j}\ ;\\ \mathrm{Intercluster}\,\mathrm{overlap}=\frac{1}{| W| }\mathop\sum \limits_{(i,j)\in W}{M}_{i,j}\ .\end{array}$$

Retrieval
Image retrieval

For the image retrieval task, latent embeddings of all images in the ID-STED and OOD-STED classification datasets (SO, NAS, Px and PR) were generated using the STED-FM model. Subsequently, an iterative retrieval process was performed. In each iteration, a single image embedding served as the template. The cosine similarity was computed between this template embedding and all other image embeddings in the dataset. These similarity scores were then used as prediction scores for performance evaluation.

More specifically, to evaluate the retrieval performance, the area under the receiver operating characteristic (ROC) curve (AUROC)117 wasused. The ROC curve, in this binary classification context, was constructed by calculating the true- and false- positive rates across a range of similarity score thresholds (Fig. 2f). For each template, a one-versus-all approach was adopted, where the positive class consisted in images belonging to the same class as the template, and all other images constituted the negative class. The AUROC was calculated for each template and averaged across all images for all classification datasets to provide a single metric performance. On all downstream datasets, the performance of a model was reported as the difference between its performance and the best model’s performance.

Patch retrieval

The patch-retrieval task follows a similar procedure, but instead of considering image embeddings as templates and candidates, we used patch embeddings, which can be easily retrieved from the ViT architecture. We started by choosing a patch in an image (or a collection of patches) containing a structure of interest and extracted its embedding from ViT-S as template. In the case of a structure of interest spanning more than a single patch (a region of more than 16 pixels by 16 pixels), we averaged the patch embeddings in which the structure accounts for more than 50% of the patch’s pixels. For all images of a given dataset, we gathered patch embeddings and ranked them in order of similarity to the template patch using cosine distance.

We performed the patch-retrieval experiment with all pretrained models, and for a given template, we only kept the top ten candidates from each model (50 images in total from five pretrained models). For quantification we performed a user study in which experts were asked to rank the 50 images (pairwise ranking, corresponding to the 50 most-similar embeddings set) according to their similarity to the template image. This produced an expert-defined similarity ranking from which we extracted the top ten most similar images. We counted the proportion of these ten candidates that were produced by each of the different pretrained models (Fig. 2h,i), which was used to quantify patch-retrieval performance.

Automatic patch-retrieval experiment

The automatic patch-retrieval experiment was performed on the F-actin conformation dataset55. The template was obtained by manually annotating a structure of interest in an image. In the case of a template spanning more than a single patch, we averaged the patches in which the template accounts for more than 50% of the patch’s pixels.

This template embedding was compared to the embeddings of all patches on large fields of view. The large field of view was cropped by extracting overlapping crops of 224 × 224 pixels (25% overlap). To avoid potential orientation bias of the selected structure of interest, the initial template was augmented through rotation. Four distinct template orientations were generated by applying successive 90∘ rotations. Each of these four rotated template embeddings was then compared against the embeddings of the image crops from the field of view. The maximum similarity score (cosine distance) achieved between any of the four templates and an image patch was used for that patch. For overlapping crops the similarity score was averaged. The resulting maximum projection heatmap was upscaled to input size and overlaid on the large field of view in Fig. 2j.

The capacity of the pretrained models to accurately identify relevant regions was evaluated against a manually annotated dataset. The dataset was composed of 79 manually annotated images for three structures: nanoclusters, compact assemblies and spines. The performance of each pretrained model was compared to a baseline detection method using class-specific intensity thresholds. The primary evaluation metric was the difference in precision between a pretrained model (Pr) and the thresholding method (Prthresh.), analyzed over the range of recall. Additionally, the performance of a random baseline was reported. This random model simulated chance-level detection by randomly reassigning the expert annotations within the foreground pixels of the field of view of the image.

Fine-tuningClassification

Downstream classification performance was evaluated by adding a linear layer with batch normalization on top of the pretrained encoders. All models compared share the same backbone and classification head architectures. We then either kept the pretrained features frozen and only fine-tuned the linear layer (linear probing) or allowed for end-to-end fine-tuning (fine-tuning). All models were trained with the cross-entropy loss. Early stopping was used to checkpoint the best validation loss during fine-tuning. In all classification experiments, training was repeated with five random seeds (42, 43, 44, 45 and 46).

Linear probing

We use stochastic gradient descent (SGD) with a linear warmup schedule that takes the learning rate from 0.0 to 0.001 in the first 30 epochs. Afterwards, a cosine annealing scheduler118 with a period of 30 epochs was applied for the remaining 270 epochs, for a total of 300 epochs of fine-tuning. Cosine annealing was carried out with maximum and minimum learning rate values of 10−3 (the value reached after the linear warmup) and 10−5, respectively.

Fine-tuning

The models were fine-tuned for 300 epochs. The Adam optimizer was used. The scheduler uses a linear warmup schedule that takes the learning rate from 0.0 to 10−4 in the first 30 epochs. A cosine annealing scheduler was applied for the remaining training epochs, annealing the learning rate from 10−4 and 10−6.

Random initialization: from scratch

We also trained the models from scratch (random initialization) using a fully supervised training scheme with the annotated data associated with the downstream task. For this configuration we used the Adam optimizer with a linear warmup scheduler for 30 epochs followed by a cosine decay scheduler over the remaining epochs. The models trained from scratch share the same backbone and classification head architectures as the pretrained models.

Segmentation

We evaluated segmentation performance by adding a linear layer to the pretrained encoder. All models compared share the same backbone and linear layer architectures. Letting B be the batch size, Np the number of patches, Dp the patch embedding dimension, P the patch size (in pixels, assuming square patches) and C the number of channels to predict (classes), the encoder outputs a tensor of dimensions (B, Np, Dp). The linear layer was trained to map these patch embeddings to pixel values (in the range [0,1]), transforming the encoder’s output (excluding the class token embedding, hence Np − 1 patches) to a tensor of dimension (B, Np − 1, P2C). The output of this linear layer was then reconstructed into image space (a process called ‘unpatchifying’) to match the original input dimensions, enabling the computation of MSE loss against the ground truth segmentation mask. For classification, we considered linear probing and fine-tuning. For all training, early stopping was used to checkpoint the best validation loss during fine-tuning. The models were trained for 300 epochs. In all segmentation experiments, training was repeated with five random seeds (42, 43, 44, 45 and 46).

Linear probing

When using linear probing, we used SGD with a linear warmup of 30 epochs, followed by cosine annealing for the remaining epochs using maximum and minimum learning rates of 10−3 and 10−5, respectively, along with a period of 30 epochs.

Fine-tuning

For end-to-end fine-tuning we used the same schedulers, this time removing the 30-epoch period and replacing the SGD optimizer with the AdamW optimizer, using a learning rate of 10−3, weight decay of 0.1 and β parameters of 0.9 and 0.95.

Random initialization: from scratch

When training from scratch, only the hyperparameters of the AdamW optimizer were different from the end-to-end case, with a learning rate of 10−3, weight decay of 0.05 and β parameters of 0.9 and 0.999. The models trained from scratch shared the same backbone and linear layer architectures as the pretrained models.

UNETR decoder

For some experiments, we used a larger decoder than a simple linear layer to maximize performance gains. The decoder that was used closely followed the UNETR architecture119. It was used in segmentation, denoising and algorithmic super-resolution experiments (Supplementary Figs. 17–21). The performance gains obtained from using this large decoder rather than the simple linear layer for segmentation are also shown in Supplementary Fig. 12.

Small-data regime

For both classification and segmentation, we also considered the small-data regime, in which the number of annotated instances for fine-tuning was limited. For classification, we used {10, 25, 50 and 100} annotated instances per class for the linear probing or fine-tuning steps. For datasets with insufficient instances to meet these counts, the maximum available number of instances per class was used (Supplementary Table 3). For segmentation tasks, we considered a percentage of training samples rather than a raw count, using a ratio of {0.01, 0.1, 0.25 and 0.50} of available annotated samples for linear probing or fine-tuning steps.

To reduce variability in performance caused by different number of weight updates when using smaller datasets, we adopted a constant training budget. For all models, whether trained from scratch or fine-tuned from previous pretraining, the budget was set to match the number of parameter updates used in the full dataset fine-tuning scenario, with an upper limit of 1,000 training epochs. More specifically, we define the training budget in the full dataset scenario as Bf = Nt × Ne, where Nt is the number of annotated training instances and Ne is the fixed number of training epochs. The small data regime training budget Bs,classif in classification was computed as:

$${B}_{s,\mathrm{classif}}=\min \left(1,000,\frac{{B}_{f}}{{N}_{c}\cdot C}\right)$$

where Nc is the number of training instances per class and C is the number of classes. In segmentation, the training budget Bs,seg was computed as:

$${B}_{s,\mathrm{seg}}=\min \left(1,000,\frac{{B}_{f}}{P\cdot {N}_{t}}\right)$$

where P is the percentage of training samples. The optimizers, loss functions and hyperparameters (other than those pertaining to training epochs) were identical to those described in the full-dataset experiments.

Structural complexity and model generalizabilityQuantifying domain distance

To establish a quantitative metric for describing the distance between the pretraining dataset and each downstream task dataset, we used a frequency-based approach. Measuring distances between image domains presents an open challenge. Metrics based on deep learning features (for example Fréchet Inception Distance and Inception Score) are common in computer vision59,60,61,62,63 but recent work showed that they can fail to capture diversity and perceptual quality in specific contexts86,87. Moreover, because these metrics rely on feature extractors pretrained on natural images, they may not be ideally suited for OOD microscopy data88. Metrics based on direct pixel comparison (for example, MSE or SSIM) are highly sensitive to spatial shifts and thus unreliable to measure the distance between images with different biological structures.

To assess domain distance between images from different biological structures and acquired with various microscopy techniques, we decided to rather use the frequency content of the images, leveraging a normalized power spectrum analysis. As ref. 64 demonstrated, microscopy images have distinct power spectrum signature that can be used to infer the quality. They also point out that spectral domain approaches are more easily applicable to comparing different images, than pixel-wise metrics. The distance between two datasets was quantified by measuring the Kullback–Leibler divergence between the normalized power spectrum density of two images120,121. The distance between two datasets corresponds to the average Kullback–Leibler divergence between all pairs of images. For large datasets we sampled n = 5,000 images.

Correlation with downstream performance

The power spectrum-based distance was correlated with the downstream model performance across all evaluated tasks (classification and segmentation). To enable the comparison across tasks with different dynamic ranges, both the distance values and the performance metrics (accuracy for classification (F1-score for HPA classification) and area under the precision–recall curve for segmentation) were z-score-standardized within each specific task.

Evaluating pretraining dataset diversity

As a metric for dataset diversity, we computed the average intra-dataset distance between images, using the power spectrum-based metric detailed above. A larger average intra-dataset distance indicates greater variability in structural texture and spatial frequency content across the pretraining image set. The Pearson correlation coefficient between the dataset diversity and the average downstream performance across all tasks was then computed (accuracy for classification (F1-score for HPA classification) and area under the precision–recall curve for segmentation). The performance within each downstream dataset was z-score standardized.

Quantifying segmentation difficulty

To analyze the relationship between structural properties and performance of the downstream segmentation tasks, we incorporated a quantitative measure of segmentation difficulty based on object morphology. Following previous work58, we used the perimetric complexity (PC) as the metric. PC is defined by the following equation:

$$\,\text{PC}\,=\dfrac{{P}^{2}}{2\pi A},$$

where p denotes the perimeter of the segmented structure and A denotes its area. Higher PC values correspond to increasingly complex or irregular object morphology.

Image restorationDenoising

To enable image-to-image denoising, a dedicated decoder was integrated into the STED-FM architecture. The decoder design was heavily inspired by the UNETR (UNet Transformer) model, adapted specifically for two-dimensional segmentation tasks119.

The decoder structure utilizes skip connections originating from the ViT-S encoder’s intermediate layers, specifically {z3, z6, z9 and z12}. These features are projected and concatenated into the corresponding upsampling blocks. The feature map depths in the decoder blocks that process these skip connections were configured with filter counts {64, 128, 256 and 512}, respectively. Each subsequent deconvolution block performs upsampling while systematically halving the number of filters. The final output block consisted of two sequential convolutional layers, followed by a single terminal convolutional layer that projected the feature maps to the desired number of output classes. The model’s final output was then passed through a sigmoid activation function.

During training, the STED-FM encoder was kept frozen. We trained the decoder for 300 epochs with the AdamW optimizer with a weight decay of 0.01 and β values of (0.9 and 0.999). The learning rate was set at 1 × 10−4 and used a linear warmup schedule that takes the learning rate from 0.0 to 1 × 10−4 in the first 30 epochs. Afterwards, a cosine annealing scheduler118 with a period of 30 epochs was applied for the remaining 270 epochs, for a total of 300 epochs of fine-tuning. Cosine annealing was carried out with maximum and minimum learning rate values of 10−4 (the value reached after the linear warmup) and 10−6, respectively.

We compared STED-FM with four baselines: CARE2D65, N2V66, Pix2Pix67 and UNet-RCAN68. For CARE2D, N2V and Pix2Pix we used the implementation provided in ZeroCostDL4Mic and DL4MicEverywhere122,123. In all cases, we used the default training parameters and trained for 300 epochs. For the UNet-RCAN, we used the training scripts provided in the original publication. We kept the same training parameter configuration and trained for 200 epochs as in the seminal paper.

Algorithmic super-resolution

For the simple algorithmic super-resolution task involving the VGAT-SR dataset, we used the same training procedure as with the denoising task.

For the algorithmic super-resolution task on the F-Actin-SR dataset, we used the seminal implementation of Pix2Pix67, as well as a DDIM following the implementation of124. We used 1,000 diffusion timesteps for training the model and 100 denoising steps for the DDIM sampling. We used a linear β schedule. The denoising network within the DDIM was based on a UNet architecture with residual connections and attention mechanisms. It consisted of three encoder stages with channel multipliers (1, 2 and 4) applied to a base dimension of 64, followed by a bottleneck and three symmetric decoder stages with skip connections. Each encoder and decoder contained two ResNet blocks with root mean square normalization and sigmoid linear unit activation functions, followed by an attention layer. We used linear attention for computational efficiency in the outer stages and full self-attention in the innermost stage. Timestep information was embedded using sinusoidal positional encodings and processed through a multi-layer perceptron. These timestep embeddings modulate the ResNet block features via affine transformations (scale and shift parameters). We trained for 300 epochs, using the Adam optimizer with a learning rate of 2 × 10−4 and β coefficients of 0.9 and 0.99.

We then fine-tuned the DDIM using the procedure described in DRaFT70. Rather than optimizing the standard denoising objective, DRaFT directly optimizes a differentiable reward function by backpropagating through the deterministic DDIM sampling process. We used the negative MSE between STED-FM’s embeddings of the real and generated images as reward signal. To enable memory-efficient fine-tuning, we applied LoRA71 to the linear and convolution layers of the denoising network with a rank of 8, thereby only training a small subset of adaptor parameters while keeping the base DDIM frozen. We also used gradient checkpointing during the backpropagation through sampling steps, which reduces memory consumption by recomputing intermediate activations during the backward pass. The total loss to minimize combined the negative reward objective (with a weight of 1.0) with the standard denoising loss (with a weight of 0.1) to maintain training stability. We used 100 deterministic DDIM sampling steps (η = 0) and backpropagated through only the last sampling step (DRaFT-1 variant) to balance computational efficiency with gradient signal quality. Optimization was performed using the Adam optimizer with a learning rate of 1 × 10−4 and β coefficients of 0.9 and 0.99. Training was performed over 20 epochs. We performed this training over varying training set sizes ([50, 100, 300, 500, 1,000, 2,000, 3,000 and 4,331] images) to evaluate performance in the low-data regime. Every training configuration was performed for five different seeds.

To evaluate the generation of the F-actin nanostructures we initially used a similar procedure to ref. 69. We found pixel-wise metrics such as MSE, peak SNR and SSIM to be unreliable for comparison of the synthetic images with the real images, as they tend to reward blurry images which fail to reconstruct the fine-grained structures of F-actin. We therefore chose metrics that better capture the quality and visual fidelity of STED F-actin images: the HF-FMC and the LPIPS metric63. For the former, we compute the Pearson correlation between flattened two-dimensional Fourier magnitude spectra (FMC), and additionally report low- and high-frequency band-limited variants (LF-FMC and HF-FMC). To split into low and high-frequency bands, we set a spatial frequency cutoff of 10 pixels. With a pixel size of 20 nm for this dataset, the LF-FMC measures the capacity of generating structures broader than roughly 200 nm, and the HF-FMC, those smaller than 200 nm. This was chosen due to the well-known ring structure of the F-actin protein, reported in ref. 54, which is periodic at 190 nm. For LPIPS, we used the implementation provided in the TorchMetrics library125, with AlexNet as feature extractor126. To further assess the visual fidelity of the synthetic images we created a user study. We showed eight experts a true STED image (n = 26) as well as three generated images obtained from Pix2Pix, the pretrained diffusion model (named DDIM for the sampling procedure used) and the DRaFT-fine-tuned diffusion model using STED-FM, all conditioned on the confocal version of the original image. The experts were then asked to select which of the three generated images was most similar to the true STED.

Image generationLatent-guided denoising diffusion probabilistic models

Following the latent guidance framework74, we conditioned the DDPM using a 384-dimensional latent vector z obtained by passing an image through STED-FM. To condition the DDPM, we map z to the dimensionality of the timestep embedding t’s latent space (256 dimensions). The resulting embeddings were then added (z + t, Fig. 4a) and serve as the conditioning input. Once the latent-guided DDPM was trained, a noise image xT can be given to the DDPM along with the latent code z of a test image x0. The DDPM generates a new image which preserves the features present in image x0.

For classifier-free guidance73, a conditioning vector was obtained by creating an embedding layer for 24 protein classes that were defined in a subset of the STED-FM dataset (Supplementary Table 12), producing a 256-dimensional vector that matches the timestep-embedding dimension. The latent vector was then added to the timestep embedding for conditioning (z + t; Fig. 4a).

Latent attribute manipulation

For latent attribute manipulation, we followed the method from ref. 75, originally developed for generative adversarial networks (GANs) and later adapted to DDPMs74. The method manipulates image semantics in latent space using the normal vector of a SVM’s decision boundary, trained to separate two classes (Fig. 4c). The SVM’s decision boundary is a hyperplane in d-dimensional space, from which we can extract its normal vector \({\bf{n}}\in {{\mathbb{R}}}^{d}\). For an image embedding z in this latent space, we computed the signed distance from z to the hyperplane as

$$d({\bf{n}},{\bf{z}})={{\bf{n}}}^{\top }{\bf{z}}+b\ ,$$

(1)

where b is the intercept of the decision boundary. To manipulate the image embedding z in the direction of the normal vector to a target distance dt from the hyperplane, we updated it along the direction of the normal vector n

$${{\bf{z}}}^{{\prime} }={\bf{z}}+({d}_{t}-d({\bf{n}},{\bf{z}}))\cdot {\bf{z}}\ .$$

(2)

Manipulating image semantics requires partitioning of an image dataset into two classes that represent opposing ends of the desired semantic attributes. In our case, the images were embedded using STED-FM and an SVM was trained to classify the image embeddings. The direction of the normal vector to the SVM’s hyperplane corresponds to the semantic attribute direction. We can then investigate how the image has changed as a result of the manipulation by decoding the manipulated embedding \({\bf{z}}{\prime}\) back to pixel space using the conditioned DDPM described in the previous section. In all latent attribute manipulation experiments, we shifted each image’s latent representation from the mean distance to the SVM boundary of one distribution toward the mean distance of the other distribution.

Pattern discoverySynaptic development of PSD95

To investigate age-dependent changes in PSD95 morphology, we used the Synaptic development dataset76. An SVM was trained to discriminate between the synaptic structures from cultured neurons fixed at two different time points: DIV12 and DIV25. The normal vector to the decision boundary of the SVM in the latent space was then used to manipulate the latent representation of an image of PSD95 corresponding to DIV12 neurons toward images corresponding to PSD95 in neurons at DIV25. For each DIV12 anchor image, we generated a series of six interpolated latent codes at constant intervals between the average distance of the DIV12 and DIV25 classes from the SVM boundary (Supplementary Fig. 29). Manipulated latent codes were input to the DDPM to synthesize the corresponding images, which were then subjected to further analysis.

To quantify the morphological changes induced by the latent space manipulation, we first identified protein clusters in the generated images using a wavelet segmentation method, similar to the approach described in ref. 45. Several morphological and intensity features were extracted from the segmentation: area, perimeter, eccentricity, solidity, density, intensity and number of nanodomains. These features were averaged across all identified protein clusters within each image.

To evaluate the plausibility of the features extracted from synthetic images, we calculated the percentage of images whose features were significantly different (P < 0.05) from the corresponding target distribution. For example, for both real and synthetic DIV12 images, the target distribution for a given feature was defined as the distribution of that feature’s values in the real DIV12 dataset. The P value of a data point was obtained from computing its z-score in the target distribution (Supplementary Table 11).

To gain a deeper understanding of the features that best discriminate between PSD95 nanostructures at DIV12 and DIV25, we performed a consensus clustering analysis. k-means clustering was applied by varying the number of clusters (k) from 2 to 25. A pairwise consensus matrix was constructed, indicating the frequency with which each pair of data points was clustered together out of the 23 independent k-means runs. Hierarchical clustering was then applied on the consensus clustering, from which we were able to identify five subtypes of PSD95 synaptic clusters in the images. The proportion of each subtype was measured at each step of the latent space manipulation. To assign one instance to one of the subtypes, we computed the Euclidean distance between the image’s and the subtypes’ features and assigned the image to the closest subtype (Supplementary Fig. 32).

Perforated synapses

We observed an increased prevalence of perforated synaptic structures when manipulating the latent representations of PSD95 clusters toward those of DIV25 neurons. To further characterize this effect, we performed a detailed analysis using the patch-retrieval capabilities of STED-FM. A template image was generated from the synapse shown in Fig. 5a (d = 0.98; right image) and the procedure described in ‘Automatic patch-retrieval’ experiment was applied to compute similarity maps across the training data from DIV12 and DIV25 neurons in the Synaptic development dataset. To obtain an approximate segmentation and count of perforated synapses, a similarity threshold of 0.65 was applied, and the total number of synapses was determined using the regionprops function from the scikit-image Python library127. This threshold was manually validated by an expert. The reported proportion corresponds to the number of detected perforated synapses divided by the total number of synapses identified via wavelet-based segmentation in the PSD95 images of the Synaptic development dataset.

We calculated the bootstrap distribution of perforated synapse proportion by resampling the number of perforated synapses found per image 10,000 times. For each resampling iteration, the proportion was recalculated. For statistical testing, we performed a two-tailed z-test with the null hypothesis (H0) that the mean proportions are equal (\({H}_{0}:{\mu }_{{\rm{DIV}}12}={\mu }_{{\rm{DIV}}25}\)). The standard score (Z) was calculated as:

$$Z=\dfrac{{\mu }_{{\rm{DIV}}25}-{\mu }_{{\rm{DIV}}12}}{{s}_{{\rm{DIV}}25}},$$

where s is the s.d. The P value was obtained using 2Φ(−∣Z∣), where Φ is the standard normal cumulative distribution function.

F-actin nanostructures

The activity-dependent remodeling of F-actin from rings to fibers was investigated using the training and validation datasets provided in ref. 19. To ensure unambiguous training, image crops containing both F-actin rings and fibers were excluded from the dataset used to train the SVM boundary.

For image generation, the images of the testing dataset provided in ref. 54, corresponding to high Mg2+/low Ca2+ (low activity) and Glu/Gly (high activity) conditions were used as anchors. For each crop in the testing dataset, its latent code was manipulated along the normal vector of the SVM boundary. We generated a series of six interpolated latent codes at constant intervals between the average distance of the low- and high- activity classes from the SVM boundary (Supplementary Fig. 34). Five images were generated for each anchor with uniform step sizes along the manipulation vector using the DDPM conditioned on the manipulated embeddings. To validate the morphological changes, we used the pretrained UNet model from ref. 54 to quantify the evolution of segmented F-actin rings and fibers as a function of image manipulation.

F-actin compact assemblies

Given the increased number of compact F-actin assemblies observed when manipulating the latent representations toward the low-activity condition, we performed a more detailed analysis of this pattern using the model’s patch-retrieval capability. A template representing a compact F-actin assembly was manually annotated from a real image. Using the procedure detailed in Automatic patch-retrieval experiment, we computed similarity maps for this template across the activity-dependent F-actin dataset and applied a threshold of 0.65 on those maps to generate the segmentation masks. The area of compact F-actin assemblies was quantified within dendritic regions identified using the immunostained protein MAP2 as a reference signal. Segmented regions intersecting the dendritic mask were included in the proportion calculation. The bootstrap distribution of the average proportion was calculated using 10,000 resamplings and is reported in Fig. 5i.

Automated microscopySTED microscopy experiments
STED imaging

Super-resolution imaging was performed on an Abberior Expert-Line STED system (Abberior Instruments). This system was equipped with a ×100 oil immersion objective lens with a numerical aperture of 1.4 (Olympus, model UPLSAPO100XO), a motorized stage, and an auto-focus unit. Three excitation wavelengths were used (485 nm, 561 nm and 640 nm) for the experiments. The system is equipped with a 775-nm depletion laser (40 MHz, 1.2-ns pulse duration; MPB Communications). All lasers were operated at 40 MHz. The emitted fluorescence photons were detected by APDs through a pinhole set at approximately 1 Airy unit. Red dyes were detected with a FF02-615/20-25 filter (Semrock) and far-red dyes were detected with a ET685/70 filter (Chroma). The acquired images were visualized and processed using the Fiji software (ImageJ, v.1.54p) or Python.

Sample preparation and staining procedures

Neuronal cultures were prepared as described in the section ‘Sample preparation and acquisition’. Cultures were fixed for 20 min in 4% PFA solution (PFA 4%, sucrose 4%, phosphate buffer 100 mM and Na-EGTA 2 mM). Immunostaining was performed as described in the section ‘Sample preparation and acquisition’. Labeling of F-actin with fluorescently tagged phalloidin was performed after the secondary antibodies, for 2 h. Supplementary Tables 13 and 14 summarize the antibodies used in this study with associated concentrations. F-actin was stained with phalloidin-STAR635 (Sigma-Aldrich, cat. no. 30972-20 μg, 1:50 dilution).

Workflow

The automated microscopy experiment with automatic ROI selection were performed as follows:

A confocal overview image of a large field of view was acquired on the microscope (Fig. 6 and Supplementary Fig. 36).

ROIs were identified and extracted from the overview using the developed napari plugin (Supplementary Fig. 36i). The STED-FM latent representation vectors were extracted from each image patch corresponding to the identified ROIs forming the training dataset for the random forest classifier (Supplementary Fig. 36ii). STED-FM extracts the latent representation vector of all patches in the image and the trained random forest is used to predict the associated class (Supplementary Fig. 36iii).

The ROIs were imaged using the STED microscope, with imaging parameters selected through machine learning-based optimization routines such as bandit optimization or reinforcement learning (RL) models80.

Interactive ROI selection

For interactive ROI selection, a random forest model was trained on patch embeddings obtained from the STED-FM backbone of the overview confocal image. This approach is inspired by the work of ref. 82. The interactive annotation was implemented in a napari-plugin, allowing users to annotate as many structures of interest as desired. In the experiments, the regions containing spines (or not) were annotated.

As STED-FM requires images of 224 × 224 pixels, the overview image was tiled with a 50% overlap and fed to the model. A 16 × 16-pixel patch within these crops was considered annotated if at least 25% of its area had been annotated. The extracted patch embeddings and corresponding annotations were split into training and validation sets with a 80:20 ratio. The napari plugin provides user-configurable parameters for the random forest model such as the number and maximum depth of trees. During the experiments, a configuration of 100 trees with a maximum depth of 5 was used.

To extract individual ROIs from the binary masks predicted by the random forest model, the following procedure was applied: (1) the predicted mask was converted into a labeled image, where each contiguous region (island) of positive pixels was assigned a unique ID; (2) the centroid of the bounding box center of each island was obtained by using regionprops from the scikit-image Python library127. In the experiments, ROIs of a constant, predefined size were used and centered on the centroid of the bounding box.

Benchmarking and evaluation

Quantifying the performance of an iterative annotation pipeline is non-trivial, as annotations can be iteratively updated until all ROIs were selected, making direct measurement difficult. To address this, we designed an evaluation strategy that simulated an annotator, allowing us to benchmark the performance of the random forest on a set of unseen images using a leave-one-out cross-validation scheme across five images.

We developed an iterative strategy to efficiently select the most informative training samples from unlabeled image patches, aiming to maximize classification performance while minimizing annotation effort. The process begins by extracting feature embeddings from an image using STED-FM, which then serve as the pool of available patches for training. The training set is initialized with a random 10% sample of positive (spines) patches. The same number of negative patches were added to keep the dataset balanced.

The core of the algorithm is an alternating sampling loop that sequentially adds one hard negative and one hard positive sample. The algorithm prioritizes patches that the current random forest classifier (trained on previously selected data) finds most uncertain or misclassifies (low-confidence predictions). To efficiently guide this sampling, k-means clustering is performed on the patch embeddings (16 clusters for positive patches and 64 for negative patches) to capture the heterogeneity within each class, reflecting the need for diverse training examples. Patches from high-confidence clusters were skipped to avoid redundant sampling.

After a new sample is tentatively added, the classifier is retrained and evaluated using the F1-score on the remaining patches. If the new sample improves the F1-score, it is permanently added to the training set. Otherwise, the patch yielding the highest tentative F1-score is selected to guarantee progressive model improvement. The process terminates when the F1-score on the current image reaches 0.9 or the selected number of samples hits 500 patches per image. This adaptive sampling strategy ensures exploration of the feature space by targeting misclassified examples as a user would do.

Bandit optimization
Automated ROI selection and 3D acquisition

3D-DyMIN acquisitions were performed on neuronal cultures stained for Bassoon and F-actin. For interactive ROI selection using STED-FM as previously described, spines were chosen from a confocal overview of the F-actin. At each selected location, a volume of 2.88 μm × 2.88 μm × 2 μm was acquired. Only the STED and excitation powers, and pixel dwell time were optimized. Supplementary Table 15 provides the range of each parameter. DyMIN parameters were set at a threshold of one photon detected within 20% of the pixel dwell time for steps 1 and 2 (ref. 83). The imaging optimization objectives were photobleaching, signal ratio and z-resolution. Photobleaching and signal ratio were calculated following the procedure described previously80. Z-resolution was approximated by fitting a Gaussian function to the line profile obtained from the central slices (ten above and ten below the center) of the maximal-projection of each frame. During the optimization process, the z-profile was approximated by a center-line across the summed volume, which accounts for the difference between the automatic resolution computation and the manually determined FWHM in Fig. 6b. The contextual LinTSDiag model was used for optimization with default parameters80.

STED-FM as a metric for image quality optimization

We designed an experiment using STED-FM as an optimization objective to guide image acquisition. To quantify the quality of a newly acquired image, the image was first embedded into STED-FM’s latent space. This latent representation was then passed to the pretrained SVM of Fig. 4e−g, which was trained to differentiate between low- and high-quality images. A high-quality prediction corresponds to an embedding far from the SVM’s decision boundary and having a positive score (>0). Acquisitions were performed on neuronal cultures stained for F-actin. ROIs were manually selected for this experiment, and at each location, an image of 4.48 μm × 4.48 μm was acquired. The optimization process focused on adjusting three imaging parameters: the STED power, the excitation power and the pixel dwell time. The optimization was driven by the LinTSDiag model, using the default parameters described previously80. The complete range of values for each parameter is provided in Supplementary Table 16.

Reinforcement learning

Three-color STED acquisitions were performed on neurons stained for Bassoon, PSD95 and F-actin. For each channel, a dedicated reinforcement learning (RL) model was used for parameter optimization. Specifically, we used the same proximal policy optimization model described and trained in ref. 80. The range of imaging parameters for each channel is provided in Supplementary Table 17. The imaging session followed the same methodology and default parameters as described previously80. In brief, ROIs were selected using STED-FM as previously described from an initial confocal image, spines were chosen from the F-actin signal. A confocal acquisition of a ROI was then given as input to the corresponding RL model. Based on the acquisition history, the model selected the next imaging parameters, and a STED image was acquired. A second confocal image was then acquired to quantify photobleaching. The imaging optimization objectives were measured from the acquired images and fed back to the RL model to inform future parameter selections. This iterative process was repeated for a total of 30 ROIs with the STED images acquired in this order: F-actin, PSD95 and Bassoon.

Resampling statistics

We used resampling to verify statistical differences between two groups128. The detailed procedure is described in ref. 19. When analyzing more than two groups, the approach involved resampling of the F-statistic for 10,000 iterations128. We tested the null hypothesis that all groups originate from the same underlying mean distribution, rejecting it if the calculated P value is below 0.05. Upon rejection, we conducted pairwise comparisons between each group using a two-group randomization, also performed with 10,000 repetitions128. This test randomly reassigned the data points between the two groups being compared and calculated the difference in their means. We then assessed the likelihood of observing our actual mean difference under the assumption of no true difference (the null hypothesis), again using a significance level of 0.05 to determine statistical significance.

Reporting summary

Further information on research design is available in the Nature Portfolio Reporting Summary linked to this article.