On the use of Mahalanobis distance for out-of-distribution detection
  with neural networks for medical imaging
Implementing neural networks for clinical use in medical applications
necessitates the ability for the network to detect when input data differs
significantly from the training data, with the aim of preventing unreliable
predictions. The community has developed several methods for
out-of-distribution (OOD) detection, within which distance-based approaches -
such as Mahalanobis distance - have shown potential. This paper challenges the
prevailing community understanding that there is an optimal layer, or
combination of layers, of a neural network for applying Mahalanobis distance
for detection of any OOD pattern. Using synthetic artefacts to emulate OOD
patterns, this paper shows the optimum layer to apply Mahalanobis distance
changes with the type of OOD pattern, showing there is no one-fits-all
solution. This paper also shows that separating this OOD detector into multiple
detectors at different depths of the network can enhance the robustness for
detecting different OOD patterns. These insights were validated on real-world
OOD tasks, training models on CheXpert chest X-rays with no support devices,
then using scans with unseen pacemakers (we manually labelled 50% of CheXpert
for this research) and unseen sex as OOD cases. The results inform
best-practices for the use of Mahalanobis distance for OOD detection. The
manually annotated pacemaker labels and the project's code are available at:
https://github.com/HarryAnthony/Mahalanobis-OOD-detection.
Harry Anthony, Konstantinos Kamnitsas
On the use of Mahalanobis distance for out-of-distribution detection with neural networks for medical imaging

###### Abstract

Implementing neural networks for clinical use in medical applications necessitates the ability for the network to detect when input data differs significantly from the training data, with the aim of preventing unreliable predictions. The community has developed several methods for out-of-distribution (OOD) detection, within which distance-based approaches - such as Mahalanobis distance - have shown potential. This paper challenges the prevailing community understanding that there is an optimal layer, or combination of layers, of a neural network for applying Mahalanobis distance for detection of any OOD pattern. Using synthetic artefacts to emulate OOD patterns, this paper shows the optimum layer to apply Mahalanobis distance changes with the type of OOD pattern, showing there is no one-fits-all solution. This paper also shows that separating this OOD detector into multiple detectors at different depths of the network can enhance the robustness for detecting different OOD patterns. These insights were validated on real-world OOD tasks, training models on CheXpert chest X-rays with no support devices, then using scans with unseen pacemakers (we manually labelled 50% of CheXpert for this research) and unseen sex as OOD cases. The results inform best-practices for the use of Mahalanobis distance for OOD detection. The manually annotated pacemaker labels and the project's code are available at: [https://github.com/HarryAnthony/Mahalanobis-OOD-detection](https://github.com/HarryAnthony/Mahalanobis-OOD-detection)

Keywords:Out-of-distribution Uncertainty Distribution shift.

## 1 Introduction

Neural networks have achieved state-of-the-art performance in various medical image analysis tasks. Yet their generalisation on data not represented by the training data - out-of-distribution (OOD) - is unreliable [12, 21, 33]. In the medical imaging field, this can have severe consequences. Research in the field of OOD detection [26] seeks to develop methods that identify if an input is OOD, acting as a safeguard that informs the human user before a potentially failed model prediction affects down-stream tasks, such as clinical decision-making - facilitating safer application of neural networks for high-risk applications.
One category of OOD detection methods use an **external model for OOD detection**. These include using _reconstruction models_[1, 9, 20, 22, 27], which are trained on in-distribution (ID) data and assume high reconstruction loss when reconstructing OOD data. Some approaches employ a _classifier_ to learn a decision boundary between ID and OOD data [26]. The boundary can be learned in an unsupervised manner, or supervised with exposure to pre-collected OOD data [11, 25, 29, 31]. Other methods use _probabilistic models_[15] to model the distribution of the training data, and aim to assign low probability to OOD inputs.

Another category are **confidence-based methods** that enable discriminative models trained for a specific task, such as classification, to estimate uncertainty in their prediction. Some methods use the network's softmax distribution, such as MCP [10], MCDropout [6] and ODIN [18], whereas others use the distance of the input to training data in the model's latent space [17].

A commonly studied method of the latter category is Mahalanobis distance [17], possibly due to its intuitive nature. The method has shown mixed performance in literature, performing well in certain studies [7, 14, 24, 32] but less well in others [2, 28, 30]. Previous work has explored which layer of a network gives an embedding optimal for OOD detection [3, 17]. But further research is needed to understand the factors influencing its performance to achieve reliable application of this method. This paper provides several contributions towards this end:

* Identifies that measuring Mahalanobis distance at the last hidden layer of a neural network, as commonly done in literature, can be sub-optimal.
* Demonstrates that different OOD patterns are best detectable at different depths of a network, implying that there is no single layer to measure Mahalanobis distance for optimal detection of _all_ OOD patterns.
* The above suggests that optimal design of OOD detection systems may require multiple detectors, at different layers, to detect different OOD patterns. We provide evidence that such an approach can lead to improvements.
* Created a benchmark for OOD detection by manually annotating pacemakers and support devices in CheXpert [13].

## 2 Methods

**Primer on Mahalanobis score, \(\mathcal{D}_{\mathcal{M}}\):** Feature extractor \(\mathcal{F}\) transforms input \(\mathbf{x}\) into an embedding. \(\mathcal{F}\) is typically a section of a neural network pre-trained for a task of interest, such as disease classification, from which feature maps \(h(\mathbf{x})\) are obtained. The mean of feature maps \(h(\mathbf{x})\) are used as embedding vector \(\mathbf{z}\):

\[\mathbf{z}\in\Re^{M}=\frac{1}{D^{2}}\sum_{D}\sum_{D}h(\mathbf{x}),\quad\text{ where }h(\mathbf{x})\in\Re^{D\times D\times M} \tag{1}\]

for \(M\) feature maps with dimensions \(D\!\!\times\!D\). Distance-based OOD methods assume the embedded in-distribution (ID) and OOD data will deviate in latent space, ergo being separable via a distance metric. In the latent space \(\Re^{M}\), \(N_{c}\)_training_ data points for class c have a mean and covariance matrix of
\[\mathbf{\mu_{\mathrm{c}}}=\frac{1}{N_{c}}\sum_{i=1}^{N_{c}}\mathbf{z_{i_{c}}},\ \ \mathbf{\Sigma_{\mathrm{c}}}=\frac{1}{N_{c}}\sum_{i=1}^{N_{c}}(\mathbf{z_{i_{c}}}-\bm {\mu_{\mathrm{c}}})\ (\mathbf{z_{i_{c}}}-\mathbf{\mu_{\mathrm{c}}})^{T} \tag{2}\]

where \(\mathbf{\mu_{\mathrm{c}}}\) is vector of length \(M\) and \(\mathbf{\Sigma_{\mathrm{c}}}\) is a \(M\)\(\times\)\(M\) matrix. Mahalanobis distance \(\mathcal{D_{M_{c}}}\) between embedding \(\mathbf{z}\) of a _test_ data point and the _training_ data of class c can be calculated as a sum over \(M\) dimensions [19]. The **Mahalanobis score**\(\mathcal{D_{M}}\) for OOD detection is defined as the minimum Mahalanobis distance between the test data point and the class centroids of the training data,

\[\mathcal{D_{M_{c}}}(\mathbf{x})=\sum_{i=1}^{M}(\mathbf{z}-\mathbf{\mu_{\mathrm{c }}})\ \mathbf{\Sigma_{\mathrm{c}}}^{-1}\ (\mathbf{z}-\mathbf{\mu_{\mathrm{c}}})^{T},\ \ \ \ \ \mathcal{D_{M}}(\mathbf{x})=\min_{c}\left\{\mathcal{D_{M_{c}}}(\mathbf{x})\right\}. \tag{3}\]

Threshold \(t\), chosen empirically, is then used to separate ID (\(\mathcal{D_{M}}\)\(<\)\(t\)) from OOD data (\(\mathcal{D_{M}}\)\(>\)\(t\)). Score \(\mathcal{D_{M}}\) is commonly measured at a network's last hidden layer (LHL) [2, 4, 5, 23, 28, 30]. To analyse the score's effectiveness with respect to where it is measured, we extracted a separate vector \(\mathbf{z}\) after each network module (Fig. 1). Herein, a _module_ refers to a network operation: convolution, batch normalisation (BN), ReLU, addition of residual connections, pooling, flatten. Stats \(\mathbf{\mu_{\mathrm{c}}}^{\ell}\) and \(\mathbf{\Sigma_{\mathrm{c}}}^{\ell}\) (Eq. 2) of the training data were measured after each module \(\ell\), and for each input an OOD score \(\mathcal{D_{M}^{\ell}}\) was calculated per module (Eq. 3).

**Weighted combination:** Weighted combination of Mahalanobis scores \(\mathcal{D_{M}^{\ell}}\), measured at different layers \(\ell\), was developed [17] to improve OOD detection:

\[\mathcal{D_{M,\mathit{comb}}}(\mathbf{x})=\sum_{\ell}\alpha_{\ell}\ \mathcal{D_{M}^{\ell}}( \mathbf{x}), \tag{4}\]

using \(\alpha_{l}\)\(\in\)\(\Re\) to down-weight ineffective layers. Coefficients \(\alpha_{l}\) are optimised using a logistic regression estimator on pre-collected OOD data [17].

**Fast gradient sign method (FGSM) [8, 17]:** Empirical evidence showed that the rate of change of Mahalanobis distance with respect to a small input perturbation is typically greater for ID than OOD inputs [17, 18]. Therefore,

Figure 1: (Left) Method to extract embeddings after a network module. (Right) Mahalanobis score \(\mathcal{D_{M}}\) of an input to the closest training class centroid.
perturbations \(\mathbf{x}^{\prime}=\mathbf{x}-\varepsilon\cdot\text{sign}(\nabla_{x}\mathcal{D}_{ \mathcal{M}}(\mathbf{x}))\) of magnitude \(\varepsilon\) are added to image \(\mathbf{x}\), to minimise distance \(\mathcal{D}_{\mathcal{M}_{c}}\) to the nearest class centroid. Mahalanobis score \(\mathcal{D}_{\mathcal{M}}(\mathbf{x}^{\prime})\) of the perturbed image \(\mathbf{x}^{\prime}\) is then used for OOD detection.

**Multi-branch Mahalanobis (MBM):** During this work it was found that different OOD patterns are better detected at different depths of a network (Sec. 3). This motivated the design of a system with multiple OOD detectors, operating at different network depths. We divide a network into parts, separated by downsampling operations. We refer to each part as a _branch_ hereafter. For each branch \(b\), we combine (with summation) the scores \(\mathcal{D}_{\mathcal{M}}^{\ell}\), measured at modules \(\ell\!\in\!L_{b}\), where \(L_{b}\) is the set of modules in the branch (visual example in Fig. 5). For each branch, we normalise each score \(\mathcal{D}_{\mathcal{M}}^{\ell}\) before summing them, to prevent any single layer dominating. For this, the mean (\(\mu_{b}^{\ell}=\mathbb{E}_{\mathbf{x}\in X_{train}}[D_{M}^{\ell}(\mathbf{x})]\)) and standard deviation (\(\sigma_{b}^{\ell}=\mathbb{E}_{x\in X_{train}}[(D_{M}^{\ell}(\mathbf{x})-\mu_{b }^{\ell})^{2}]^{\frac{1}{2}}\)) of Mahalanobis scores of the _training data_ after each module were calculated, and used to normalise \(\mathcal{D}_{\mathcal{M}}^{\ell}\) for any _test_ image \(\mathbf{x}\), as per Eq. 5. This leads to a different Mahalanobis score and OOD detector per branch (4 in experiments with ResNet18 and VGG16).

\[\mathcal{D}_{\mathcal{M},\text{\emph{branch-b}}}(\mathbf{x})=\sum_{\ell\in L_ {b}}\frac{\mathcal{D}_{\mathcal{M}}^{\ell}(\mathbf{x})-\mu_{b}^{\ell}}{\sigma _{b}^{\ell}}. \tag{5}\]

## 3 Investigation of the use of \(\mathcal{D}_{\mathcal{M}}\) with Synthetic Artefacts

The abilities of Mahalanobis score \(\mathcal{D}_{\mathcal{M}}\) were studied using CheXpert [13], a multi-label collection of chest X-rays. Subsequent experiments were performed under three settings, summarised in Fig. 2. In the first setting, studied here, we used scans containing either Cardiomegaly or Pneumothorax. We trained a ResNet18 on 90% of these images to classify between the two classes (ID task), and held-out 10% of the data as ID test cases. We generated an OOD test set by adding a synthetic artefact at a random position to these held-out images.

**Square artefact:** Firstly, grey squares, of sizes 10, 7.5 and 5 % of the image area, were introduced to create the OOD cases. We processed ID and OOD data,

Figure 2: a) Visual and b) quantitative summary of the synthetic (setting 1) and real (setting 2 & 3) ID and OOD data used to evaluate OOD detection performance.
measured their \(\mathcal{D_{M}}\) after every module in the network and plotted the AUROC score in Fig. 3. We emphasize the following observations. The figure shows that larger square artefacts are easier to detect, with this OOD pattern being easier to detect in earlier layers. Moreover, we observed that AUROC is poor at the last hidden layer (LHL), which is a common layer to apply \(\mathcal{D_{M}}\) in the literature [2, 4, 5, 23, 28, 30]. The performance of this sub-optimal configuration may be diverting the community's attention, missing the method's true potential. The results also show AUROC performance in general improves after a ReLU module, compared to the previous convolution and BN of the corresponding layer. Similar results were found with VGG16 but not shown due to space constraints.

**Ring artefact**: The experiments were repeated with a white ring as the synthetic artefact, and results were compared with the square artefact (Fig. 4). The figure shows the AUROC for different OOD patterns peak at different depths of the network. The figure shows the layers and optimised linear coefficients \(\alpha_{l}\) for each artefact for \(\mathcal{D_{M,comb}}\) (Eq. 4), highlighting that the ideal weighting of distances for one OOD pattern can cause a degradation in the performance for another, there is no single weighting that optimally detects both patterns. As the types of OOD patterns that can be encountered are unpredictable, the idea of searching for an optimal weighting of layers may be ill-advised - implying a different application of this method is required.

## 4 Investigation of the use of \(\mathcal{D_{M}}\) with Real Artefacts

To create an OOD benchmark, we manually labelled 50% of the frontal scans in CheXpert based on whether they had a) no support device, b) any support

Figure 3: AUROC (mean of 3 seeds) for Mahalanobis score over the modules of ResNet18 for synthetic square artefacts of size 10% (purple), 7.5% (green) and 5% (blue) of the image. The module types of ResNet18 are visualised, showing AUROC is typically improved after a ReLU module. The downsample operations are shown by dashed grey lines. The AUROC at the last hidden layer (LHL) is highlighted in orange, exhibiting a comparatively poor performance.
devices (e.g. central lines, catheters, pacemakers), c) definitely containing a pacemaker, d) unclear. This was performed because CheXpert's "support devices" class is suboptimal, and to separate pacemakers (distinct OOD pattern). Findings from the synthetic data were validated on two real OOD tasks (described in Fig.2). For the first benchmark, models were trained with scans with no support devices to classify if a scan had Pleural Effusion or not (ID task). Images containing pacemakers were then used as OOD test cases. For the second benchmark, models were trained on males' scans with no support devices to classify for Pleural Effusion, then females' scans with no support devices were used as OOD test cases. For both cases, the datasets were split using 5-fold cross validation, using 80% of ID images for training and the remaining 20% as ID test cases.

**Where to measure \(\mathcal{D}_{\mathcal{M}}\):** Figure 5 shows the AUROC for unseen pacemaker and sex OOD tasks when \(\mathcal{D}_{\mathcal{M}}\) is measured at different modules of a ResNet18. The figure validates the findings on synthetic artefacts: applying \(\mathcal{D}_{\mathcal{M}}\) on the LHL can result in poor performance, and the AUROC performance after a ReLU module is generally improved compared to the preceding BN and convolution. Moreover, it shows that the unseen pacemaker and sex OOD tasks are more detectable at different depths of ResNet18 (modules 51 and 44 respectively). As real-world OOD patterns are very heterogeneous, this motivates an optimal OOD detection system having multiple detectors, each processing features of a network at different layers responsible for identifying different OOD patterns.

**Compared methods:** The OOD detection performance of multi-branch Mahalanobis (MBM) was studied. MBM was also investigated using only distances after ReLUs, as experiments on synthetic OOD patterns suggested this may be beneficial. The impact of FGSM (Sec. 2) on MBM was also studied. This was compared to OOD detection baselines. The softmax-based methods used were MCP [10], MCDropout [6], Deep Ensembles [16] (using 3 networks per k-fold),

Figure 4: AUROC (mean of 3 seeds) for Mahalanobis score over the modules of ResNet18 for synthetic grey square (purple) and white ring (orange) artefacts. The layers used for \(\mathcal{D}_{\mathcal{M},comb}\)[17] (Sec. 2) are highlighted in blue, and the weightings \(\alpha_{l}\) for each layer (Eq. 4) are shown on the right for each artefact. The results show the ideal weighting for one artefact causes a degradation in performance for another - implying there’s no one-fits-all weighting.

ODIN [18] (optimising temperature \(\mathrm{T}\in[1,100]\) and perturbation \(\varepsilon\in[0,0.1]\)). The performance was also compared to distance-based OOD detection methods such as \(\mathcal{D}_{\mathcal{M}}\), \(\mathcal{D}_{\mathcal{M},comb}\) (\(\alpha_{l}=1\ \forall l\)), \(\mathcal{D}_{\mathcal{M}}\) with FGSM (using an optimised perturbation \(\varepsilon\in[0,0.1]\)) and \(\mathcal{D}_{\mathcal{M}}\) at the best performing network module.

Performance of OOD methods for both ResNet18 and VGG16 are shown in Table 1. Results show that \(\mathcal{D}_{\mathcal{M},comb}\) without LHL outperforms the original weighted combination, showing that the LHL can have a degrading impact on OOD detection. MBM results for ResNet18 in Table 1 show that the OOD patterns are optimally detected at different branches of the network (branch 4 and 3 respectively), further motivating an ideal OOD detector using multiple depths for detecting different patterns. For VGG16 these specific patterns both peak in the deepest branch, but other patterns, such as synthetic squares, peak at different branches (these results are not shown due to space limits). MBM results show that if one could identify the optimal branch for detection of a specific OOD pattern, the MBM approach not only outperforms a sum of all layers, but also outperforms the best performing single layer for a given pattern in some cases. Deducing the best branch for detecting a specific OOD pattern has less degrees-of-freedom than the best layer, meaning an ideal system based on MBM would be easier to configure. The results also show MBM performance can be improved by only using ReLU modules, and optimised with FGSM.

**Finding thresholds:** Using multiple OOD detectors poses the challenge of determining OOD detection thresholds for each detector. To demonstrate the potential in the MBM framework, a grid search optimised the thresholds for four OOD detectors of MBM using ReLU modules for ResNet18 trained on setting 3 (described in Fig.2). Thresholds were set to classify an image as OOD if any detector labeled it as such. Unseen pacemakers and unseen sex were used as OOD tasks to highlight that thresholds could be found to accommodate multiple OOD tasks. The performance of these combined OOD detectors was compared to \(\mathcal{D}_{\mathcal{M},comb}\) w/o LHL (\(\alpha_{l}=1\ \forall l\)) and \(\mathcal{D}_{\mathcal{M},comb}\) with optimised \(\alpha_{l}\) (Eq.4) where both require a single threshold, using balanced accuracy as the metric (table 2). Although optimising thresholds for all OOD patterns in complex settings would be challenging, these results show the theoretically attainable upper bound outperforms both single-layer or weighted combination techniques. Methods for configuring such multi-detector systems can be an avenue for future research.

\begin{table}
\begin{tabular}{c|c c c} \hline \hline \multirow{2}{*}{OOD detection method} & \multicolumn{3}{c}{OOD task (balanced accuracy \(\uparrow\))} \\  & \multicolumn{3}{c}{Both tasks} & Unseen sex & Pacemakers \\ \hline Mahal. score (equally weighted comb w/o LHL) & 67.64 & 64.63 & 70.37 \\ Mahal. score (weighted comb with optimised \(\alpha_{l}\)) & 68.14 & 64.89 & 70.90 \\ Multi-branch Mahal. (ReLU only) & **71.40** & **67.26** & **75.16** \\ \hline \hline \end{tabular}
\end{table}
Table 2: Balanced Accuracy for simultaneous detection of 2 OOD patterns, showing a multi-detector system can improve OOD detection over single-detector systems based on the optimal layer or optimal weighted combination of layers.
## 5 Conclusion

This paper has demonstrated with both synthetic and real OOD patterns that different OOD patterns are optimally detectable using Mahalanobis score at different depths of a network. The paper shows that the common implementations using the last hidden layer or a weighted combination of layers are sub-optimal, and instead a more robust and high-performing OOD detector can be achieved by using multiple OOD detectors at different depths of the network - informing best-practices for the application of Mahalanobis score. Moreover, it was demonstrated that configuring thresholds for multi-detector systems such as MBM is feasible, motivating future work into developing an ideal OOD detector that encompasses these insights.

#### 5.0.1 Acknowledgments.

HA is supported by a scholarship via the EPSRC Doctoral Training Partnerships programme [EP/W524311/1]. The authors also acknowledge the use of the University of Oxford Advanced Research Computing (ARC) facility in carrying out this work ([http://dx.doi.org/10.5281/zenodo.22558](http://dx.doi.org/10.5281/zenodo.22558)).
