{'fraction_non_alphanumeric': 0.027219991075412762, 'fraction_numerical': 0.008627100996578908, 'mean_word_length': 4.738264580369844, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 0, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
CRISP - Reliable Uncertainty Estimation for Medical Image Segmentation

Accurate uncertainty estimation is a critical need for the medical imaging community. A variety of methods have been proposed, all direct extensions of classification uncertainty estimations techniques. The independent pixel-wise uncertainty estimates, often based on the probabilistic interpretation of neural networks, do not take into account anatomical prior knowledge and consequently provide sub-optimal results to many segmentation tasks. For this reason, we propose CRISP a ContRastive Image Segmentation for uncertainty Prediction method. At its core, CRISP implements a contrastive method to learn a joint latent space which encodes a distribution of valid segmentations and their corresponding images. We use this joint latent space to compare predictions to thousands of latent vectors and provide anatomically consistent uncertainty maps. Comprehensive studies performed on four medical image databases involving different modalities and organs underlines the superiority of our method compared to state-of-the-art approaches.


Introduction
Deep neural networks are the de facto solution to most segmentation, classification and clinical metric estimation. However, they provide no anatomical guarantees nor any safeguards on their predictions. Error detection and uncertainty estimation methods are therefore paramount before automatic medical image segmentation systems can be effectively deployed in clinical settings.
In this work, we present a novel uncertainty estimation method based on joint representations between images and segmentations trained with contrastive learning. Our method, CRISP (ContRastive Image Segmentation for uncertainty Prediction), uses this representation to overcome the limitations of state-of-theart (SOTA) methods which heavily rely on probabilistic interpretations of neural networks as is described below.
Uncertainty is often estimated assuming a probabilistic output function by neural networks. However, directly exploiting the maximum class probability of the Softmax or Sigmoid usually leads to suboptimal solutions [6]. Some improvements can be made by considering the entire output distribution through the use of entropy [20] or by using other strategies such as temperature scaling [6].
Uncertainty may also come from Bayesian neural networks, which learn a distribution over each parameter using a variational inference formalism [9]. This enables weight sampling, which produces an output distribution that can model the prediction uncertainty. As Bayesian networks are difficult to train, they are often approximated by aggregating the entropy of many dropout forward runs [4,5]. Alternatively, a network ensemble trained with different hyperparameters can also estimate uncertainties through differences in predictions [12].
In addition to modeling weight uncertainty, referred to as epistemic uncertainty, uncertainty in the data itself (aleatoric) can also be predicted [10]. However, it has been shown that these methods are less effective for segmentation [8].
Other methods explicitly learn an uncertainty output during training. De-Vries and Taylor [3] proposed Learning Confidence Estimates (LCE) by adding a confidence output to the network. The segmentation prediction is interpolated with the ground truth according to this confidence. This confidence can also be learned after training by adding a confidence branch and finetuning a pretrained network. This enables learning the True Class Probability which is a better confidence estimate than the maximum class probability [1].
These methods can be applied to classification and, by extension, to segmentation tasks with an uncertainty prediction at each pixel. In theory, uncertainty maps should identify areas in which the prediction is erroneous. However, as these methods produce per-pixel uncertainties, they do not take into account higherlevel medical information such as anatomical priors. Such priors have been used in segmentation [23,15], but are yet to be exploited in uncertainty estimation. For instance, Painchaud et al. [16] remove anatomical errors by designing a latent space dedicated to the analysis and correction of erroneous cardiac shapes. However, this approach does not guarantee that the corrected shape matches the input image.
To this end, we propose CRISP, a method which does not take into account the probabilistic nature of neural networks, but rather uses a joint latent representation of anatomical shapes and their associated image. This paper will describe the CRISP method and propose a rigorous evaluation comparing CRISP to SOTA methods using four datasets.

CRISP
The overarching objective of our method is to learn a joint latent space, in which the latent vector of an input image lies in the vicinity of its corresponding segmentation map's latent vector in a similar fashion as the "CLIP" method does for images and text [19]. As such, a test image x whose latent vector does not lie close to that of its segmentation map y is an indication of a potentially erroneous segmentation. Further details are given below. Training. As shown in Fig. 1, at train time, CRISP is composed of two encoders: the image encoder P θ and the segmentation encoder P φ . They respectively encode an image x i and its associated segmentation groundtruth y i into latent vectors z xi ∈ Dx and z yi ∈ Dy ∀i. Two weight matrices W x ∈ D h ×Dx and W y ∈ D h ×Dy linearly project the latent vectors into a joint D h −dimensional latent space where samples are normalized and thus projected onto a hyper-sphere. As such, the image latent vector z xi is projected onto a vector h xi = Wx· zx i ||Wx· zx i || and similarly for z yi . A successful training should lead to a joint representation for which h xi ≈ h yi .
During training, images and groundtruth maps are combined into batches of B elements, X = [x 1 x 2 ...x B ] ∈ B×C×H×W and Y = [y 1 y 2 ...y B ] ∈ {0, 1} B×K×H×W for images with C channels and K segmentation classes. As mentioned before, these batches are encoded by P θ and P φ into sets of latent vectors Z X and Z Y and then projected and normalized into sets of joint latent vectors H X and H Y .
At this point, a set of 2 × B samples lie on the surface of a unit hypersphere of the joint latent space. Much like CLIP [19], the pair-wise distance between these joint latent vectors is computed with a cosine similarity that we scale by a learned temperature factor τ to control the scale of the logits. This computation is done by taking a weighted product between H X and H Y which leads to the following square matrix: S = (H X · H T Y )e τ ∈ B×B . As shown in Fig. 1, the diagonal of S corresponds to the cosine similarity of the latent image vectors with their corresponding latent groundtruth vector while the off-diagonal elements are cosine similarity of unrelated vectors.
The goal during training is to push S towards an identity matrix, such that the latent vectors h xi and h yj lie on the same spot in the joint latent space when i = j and are orthogonal when i = j. This would lead to similarities close to 1 on the diagonal and close to 0 outside of it. To enforce this, a cross-entropy loss on the rows and columns of S is used as a contrastive loss [19], CRISP also has a segmentation decoder Q ψ to reconstruct segmentation latent vectors, a critical feature for estimating uncertainty. This decoder is trained with a reconstruction loss L rec which is a weighted sum of the Dice coefficient and cross-entropy loss. The model is trained end-to-end to minimize L = L cont +L rec . Uncertainty prediction. Once training is over, the groundtruth segmentation maps Y are projected one last time into the Z and H latent spaces. This leads to a set of N latent vectorsZ ∈ N ×Dy andH ∈ N ×D h which can be seen as latent anatomical prior distributions that will be used to estimate uncertainty.
Now let x * be a non-training image and y * its associated segmentation map computed with a predetermined segmentation method (be it a deep neural network or not). To estimate an uncertainty map, x * is projected into the joint latent space to get its latent vector h x * ∈ D h . We then compute a weighted dot product between h x * and each row ofH to getS ∈ N , a vector of similarity measures between h x * and every groundtruth latent vector. Interestingly enough, the way CRISP was trained makesS a similarity vector highlighting how each groundtruth map fits the input image x * .
Then, the M samples ofZ with the highest values in S are selected. These samples are decoded to obtainȲ * , i.e. various anatomically valid segmentation maps whose shapes are all roughly aligned on x * . To obtain an uncertainty map, we compare these samples to the initial prediction y * . We compute the average of the pixel-wise difference between y * andȲ * to obtain an uncertainty map U .
As not all samples equally correspond to x * , we add a coefficient w i which corresponds to how close a groundtruth map y i is from x * . Since the joint latent space is a unit hyper-sphere, we use a von Mises-Fisher distribution (vMF) [14] centered on h x * as a kernel to weigh its distance to h yi . We use Taylor's method [22] to define the kernel bandwidth b (more details are available in the supplementary materials). We define the kernel as: 3 Experimental setup

Uncertainty metrics
Correlation. Correlation is a straightforward method for evaluating the quality of uncertainty estimates for a full dataset. The absolute value of the Pearson correlation score is computed between the sample uncertainty and the Dice score. In this paper, sample uncertainty is obtained by dividing the sum of the uncertainty for all pixels by the number of foreground pixels. Ideally, the higher the Dice is, the lower the sample uncertainty should be. Therefore, higher correlation values indicate more representative uncertainty maps. Calibration. A classifier is calibrated if its confidence is equal to the probability of being correct. Calibration is expressed with Expected Calibration Error (ECE) computed by splitting all n samples into m bins and computing the mean difference between the accuracy and average confidence for each bin. Please refer to the following paper for more details [17]. Uncertainty-error mutual information. Previous studies have computed Uncertainty-error overlap obtaining the Dice score between the thresholded uncertainty map and a pixel-wise error map between the prediction and the groundtruth segmentation map [8]. As the uncertainty error overlap requires the uncertainty map to be thresholded, much of the uncertainty information is lost. We therefore propose computing the mutual information between the raw uncertainty map and the pixel-wise error map. We report the average over the test set weighted by the sum of erroneous pixels in the image.

Data
CAMUS. The CAMUS dataset [13] consists of cardiac ultrasound clinical exams performed on 500 patients. Each exam contains the 2D apical four-chamber (A4C) and two-chamber view (A2C) sequences. Manual delineation of the endocardium and epicardium borders of the left ventricle (LV) and atrium were made by a cardiologist for the end-diastolic (ED) and end-systolic (ES) frames. The dataset is split into training, validation and testing sets of 400, 50 and 50 patients respectively. HMC-QU. The HMC-QU dataset [2] is composed of 162 A4C and 130 A2C view recordings. 93 A4C and 68 A2C sequences correspond to patients with scarring from myocardial infarction. The myocardium (MYO) of 109 A4C (72 with myocardial infarction/37 without) recordings was manually labeled for the full cardiac cycle. These sequences were split into training, validation and testing sets of 72, 9 and 28 patients.
Shenzen. The Shenzen dataset [7] is a lung X-ray dataset acquired for pulmonary tuberculosis detection. The dataset contains 566 postero-anterior chest radiographs and corresponding manually segmented masks to identify the lungs. The dataset was split into training and validation sets of 394 and 172 patients. JSRT. We use the Japanese Society of Radiological Technology (JSRT) [21] lung dataset which contains images and segmentation maps for 154 radiographs with lung nodules, and corresponding segmentation masks.

Implementation details
CRISP was compared to several SOTA methods mentioned before. To make comparison fair, every method use the same segmentation network (an Enet [18] in our case). All methods were trained with a batch size of 32 and the Adam optimizer [11] with a learning rate of 0.001 and weight decay of 1e-4. We added early stopping and selected the weights with the lowest validation loss. The Entropy method was tested using the baseline network. We tested MC Dropout by increasing the baseline dropout value from 10% to 25% and 50% (we report best results with respect to the Dice score) and computing the average of 10 forward passes. For LCE, we duplicated the last bottleneck of the Enet to output confidence. The Confidnet method was trained on the baseline Enet pre-trained network. The full decoder was duplicated to predict the True Class Probability. For methods or metrics that require converting pixel-wise confidence (c) to uncertainty (u), we define the relationship between the two as u = 1 − c as all methods produce values in the range [0, 1].
To highlight some limitations of SOTA methods, we also added a naïve method for computing uncertainty which we referred to as Edge. The uncertainty map for Edge amounts to a trivial edge detector applied to the predicted segmentation map. The resulting borders have a width of 5 pixels.
As our CRISP method can be used to evaluate any image-segmentation pair, regardless of the segmentation method, we tested it on all the segmentation methods that produce different results (baseline, MC Dropout, LCE). This allows for a more robust evaluation as the evaluation of uncertainty metrics is directly influenced by the quality of the segmentation maps [8]. The value of M was determined empirically and kept proportional to the size ofZ. It can be noted, that the vMF weighting in the latent space attenuates the influence of M .

Experimental setup
We report results on both binary and multi-class segmentation tasks. As our datasets are relatively large and homogeneous, Dice scores are consistently high. This can skew results as methods can simply predict uncertainty around the prediction edges. Thus, as mentioned below, we tested on different datasets or simulated domain shift through data augmentation.
Tests were conducted on the CAMUS dataset for LV and MYO segmentation. We simulated a domain shift by adding brightness and contrast augmentations (factor=0.2) and Gaussian noise (σ 2 = 0.0001) with probability of 0.5 for all test images. We used the 1800 samples from the training and validation sets to make up theZ set and used M = 50 samples to compute the uncertainty map.
We also tested all methods trained on the CAMUS dataset on the HMC-QU dataset for myocardium segmentation. We added brightness and contrast augmentations (factor=0.2) and RandomGamma (0.95 to 1.05) augmentations during training and normalized the HMC-QU samples using the mean and variance of the CAMUS dataset. We used the A4C samples from the CAMUS dataset (along with interpolated samples between ES and ED instants) to create the set Finally, we tested our method on a different modality and organ by using the lung X-ray dataset. We trained all the methods on the Shenzen dataset and tested on the JSRT dataset. We normalized JSRT samples with the mean and variance of the Shenzen dataset. We used the 566 samples from the Shenzen dataset to form theZ set and used M = 25 samples to compute the uncertainty.

Results
Uncertainty maps are presented in Fig. 2 for samples on 3 datasets. As can be seen, Entropy, ConfidNet, and MCDropout have a tendency to work as an edge detector, much like the naive Edge method. As seen in Table 1, different methods perform to different degrees on each of the datasets. However, CRISP is consistently the best or competitive for all datasets for the correlation and MI metrics. ECE results for CRISP are also competitive but not the best. Interestingly, the trivial Edge method often reports the best ECE results. This is probably due to the fact that errors are more likely to occur near the prediction boundary and the probability of error decreases with distance. These results might encourage the community to reconsider the value of ECE for specific types of segmentation tasks. Fig. 3 shows the distribution of pixel confidence according to the well-classified and misclassified pixels. This figure allows for a better understanding of the different shortcomings of each method. It clearly shows that both MC Dropout and  Confidnet methods produce over-confident results. On the other hand, LCE appears to produce slightly under-confident predictions which explains the higher mutual information value. Finally, CRISP is the only method that can clearly separate certain and uncertain pixels. These results are consistent with what is observed in Fig. 2 as both MC Dropout and Confidnet produce very thin uncertainty and LCE predicts large areas of uncertainty around the border. Only CRISP produces varying degrees of uncertainty according to the error.
It is apparent that there is a slight decrease in performance for CRISP on the JSRT dataset. This is most likely caused by the fact that the latent space is not densely populated during uncertainty estimation. Indeed, the 566 samples inZ might not be enough to produce optimal uncertainty maps. This is apparent in Fig. 2 where the uncertainty maps for the JSRT samples are less smooth than the other datasets that have more latent vectors. Different techniques such as data augmentation or latent space rejection sampling [16] are plausible solutions.

Discussion and conclusion
While empirical results indicate that all methods perform to a certain degree, qualitative results in Fig. 2 show that most SOTA methods predict uncertainty around the prediction edges. While this may constitute a viable uncertainty prediction when the predicted segmentation map is close to the groundtruth, these uncertainty estimates are useless for samples with large errors. Whereas in other datasets and modalities, the uncertainty represents the probability of a structure being in an image and at a given position, lung X-Ray and cardiac ultrasound structures are always present and are of regular shape and position. This makes the task of learning uncertainty during training challenging as few images in the training set produce meaningful errors. Compared to other approaches, CRISP leverages the information contained in the dataset to a greater degree and accurately predicts uncertainty in even the worst predictions.
To conclude, we have presented a method to identify uncertainty in segmentation by exploiting a joint latent space trained using contrastive learning. We have shown that SOTA methods produce sub-optimal results due to the lack of variability in segmentation quality during training when segmenting regular shapes. We also highlighted this with the naïve Edge method. However, due to its reliance on anatomical priors, CRISP can identify uncertainty in a wide range of segmentation predictions.

von Mises-Fisher kernel
To define the kernel used at the end of section 2, we find the maximum likelihood parameters for the mean direction, µ, and the concentration parameter, κ, describing the vMF of all the samplesH. The mean direction of the distribution is defined with where r m = ||h m ||. We estimate the concentration parameter for a D h -dimensional space using the following equation [1]: ( We use these values to define the kernel bandwidth following Taylor's method [2]:

Edge uncertainty
Edge is a simple morphological edge-detection method. Let δ and ξ be dilation and erosion operations, f n (·) a set of n successive applications of a morphological operator f (f 0 (·) is no operation) and I the predicted segmentation map, the Edge uncertainty map is computed as