Uncertainty in latent representations of variational autoencoders optimized for visual tasks
Josefina Catoni Enzo Ferrante Diego H. Milone Rodrigo Echeveste

Local well-posedness for a novel nonlocal model for cell-cell adhesion via receptor  binding
    
Mabel Lizzy RajendranSchool of Mathematics, 
Watson Building, University of Birmingham, Edgbaston, Birmingham
B15 2TT, UK, mailto:m.l.rajendran@bham.ac.ukm.l.rajendran@bham.ac.uk  and Anna ZhigunSchool of Mathematics and Physics, Queen's University Belfast, University Road, Belfast BT7 1NN, Northern Ireland, UK, mailto:A.Zhigun@qub.ac.ukA.Zhigun@qub.ac.uk 

    
============================================================================================================================================================================================================================================================================================================================================================================





Deep learning methods are increasingly becoming instrumental as modeling tools in computational neuroscience, employing optimality principles to build bridges between neural responses and perception or behavior. Developing models that adequately represent uncertainty is however challenging for deep learning methods, which often suffer from calibration problems. This constitutes a difficulty in particular when modeling cortical circuits in terms of Bayesian inference, beyond single point estimates such as the posterior mean or the maximum a posteriori. In this work we systematically studied uncertainty representations in latent representations of variational auto-encoders (VAEs), both in a perceptual task from natural images and in two other canonical tasks of computer vision, finding a poor alignment between uncertainty and informativeness or ambiguities in the images. We next showed how a novel approach which we call explaining-away variational auto-encoders (EA-VAEs), fixes these issues, producing meaningful reports of uncertainty in a variety of scenarios, including interpolation, image corruption, and even out-of-distribution detection. We show EA-VAEs may prove useful both as models of perception in computational neuroscience and as inference tools in computer vision.









§ INTRODUCTION

The interplay between neuroscience and artificial intelligence (AI) has been steadily growing and has proven mutually beneficial for both fields. Indeed, a large number of experts posit that research in `NeuroAI' is key to help develop the next generation of artificial intelligence methods <cit.>. In turn, the use of modeling tools from machine learning (ML), has proven highly effective in shedding light on how the brain acquires, processes and stores information, <cit.>. In this vein, a fruitful line of modeling work has been that of `goal-driven' approaches, which are framed in terms of a computational task that the system needs to solve. Methods employing artificial neural networks (ANNs) have been able to successfully capture features of cortical representations in multiple areas of the brain such as the visual <cit.> and auditory systems <cit.>. The main hypothesis is that optimizing an ANN for a task that is relevant for an area of the brain may reveal properties of neural coding and perception in that area <cit.>. ML hence brings powerful novel computational tools to a longstanding tradition of explaining neural properties in terms of optimal information processing <cit.>.

Perception involves making inference about non-observable variables of interest (𝐲) from information coming through our senses (𝐱), which is always partial and incomplete. Bayes rule provides an optimal way to perform computations in probabilistic scenarios <cit.>, and hence it is a natural tool to understand perception in the context of uncertainty. Indeed, Bayesian theories of perception postulate that the brain performs probabilistic inference to estimate posterior probability distributions 𝒫(𝐲|𝐱) for those non-observable (also called latent) variables 𝐲<cit.>. This computation allows to `fill-in the gaps' left by the uncertainty of the observation –captured by the likelihood function  𝒫(𝐱|𝐲)– with prior knowledge about these variables, expressed in terms of a prior distribution  𝒫(𝐲) <cit.>.

Processing of inputs by ANNs, in turn, is also often referred to as inference, and indeed point estimates of the posterior, such as the posterior mean, correspond to optimal estimates for typical loss functions such as the mean squared error <cit.>. For decades, a popular and highly effective architecture for performing inference has been that of deep convolutional neural networks (CNNs), which originally drew inspiration from sensory processing in biological systems<cit.>. It is then perhaps not surprising that for low level perceptual tasks that have been preserved over long evolutionary time-scales, optimized  CNNs provide the currently best available predictors of mean cortical neural responses <cit.>.

There are however scenarios where point estimates are not enough. In particular, optimal information fusion relies on knowledge about the uncertainty of the sources <cit.>. A classical example of this in perceptual tasks is multi-sensory integration, but its implications are not limited to neuroscience. In the healthcare domain, where ML methods are increasingly employed, diagnostics usually involve integrating results from multiple tests and imaging modalities. While deep CNNs usually achieve high levels of precision, they often suffer from calibration problems, resulting in inaccurate uncertainty reports <cit.>. This problem becomes even more evident for out of distribution examples where models may report a high degree of certainty while systematically failing in their predictions. It is then crucial to develop models that can represent uncertainty appropriately, and the research community has been working on this problem for a number of years. The dropout technique, which was initially designed as a regularization method, for instance, has been proposed as a way to estimate model uncertainty, which can be later used to compute output uncertainty in regression and classification problems <cit.>. Biological neural networks are also a source of inspiration for finding adequate solutions to this problem. In this sense, a recurrent neural network mimicking the structure of the primary visual cortex has been shown to represent full posterior distributions via sampling, while at the same time displaying characteristic features of cortical dynamics, such as stimulus dependent transient responses and oscillations <cit.>. This approach, however required knowledge about the generative model describing the likelihood function which may not always be available.



In this context, Variational Autoencoders (VAEs) <cit.> become a valuable tool to learn useful latent representations in an self-supervised fashion. These models consist of an encoder network which maps inputs 𝐱 to the parameters of latent distributions 𝒫(𝐲|𝐱) (the inference model), and a decoder network which maps samples from the latent representations 𝐲 back to the original input space 𝒫(𝐱|𝐲) (the generative model). While the original focus of these models has been to find well behaved and usually low-dimensional latent representations, improving on those from deterministic autoencoders, they also provide a means to simultaneously learn a generative and an inference model from the statistics of the data.

Here we focus on visual inference tasks and explore settings relevant for perception in biological and artificial systems. Classical work of Ref. <cit.> has shown how sparse coding can explain natural receptive fields and orientation selectivity in the cortex. Sparsity, in turn can be induced in VAEs by employing Laplacian (rather than more standard Gaussian) priors, resulting in sparse VAEs <cit.>. Indeed, when trained on the statistics of natural images, VAEs with Laplacian (but not Gaussian) priors have been shown to evolve latent representations closely mimicking natural receptive fields and orientation selectivity in cortical visual processing<cit.>. 

As it happens in other domains of machine and deep learning, the optimization of a VAE does not guarantee that uncertainty, in this case of the inferred latent variables, will be represented in a meaningful way<cit.>, and that expected basic properties of the posterior distributions will be preserved. From a Bayesian perspective it is expected that in a well behaved inference model<cit.>:


    
  * When no information is given by an observation, the inferred posterior is equal to the prior.
    
  *  As observations become progressively more informative:
        
        
  2.1 The posteriors corresponding to different images become increasingly distinct from the prior, resulting in an increasing average distance between the prior’s mean and the posteriors’ means.
        
  2.2 The posteriors corresponding to different images also become increasingly distinct from each other, resulting in an increasing variance of the posteriors' means.
        
  2.3 The variance of individual posteriors (capturing uncertainty) decreases.
         
 

We note that there are two different sources of variance in latent representations. The first refers to how the posterior mean changes with the input, which we will henceforth refer to as the signal variance. The second refers to the remaining uncertainty after having observed a given stimulus, which we will call noise variance. Similarly, we call signal mean the distance between the prior’s mean and the posteriors’ mean. The noise mean will be zero in our models, as habitually assumed for VAEs.



If we take for instance the case of natural images, contrast is one of the features that regulates how informative an image is. In this context, the posterior inferred from images with zero contrast should match the prior distribution (Fig <ref>). Moreover, one would expect an increase in signal mean and variance for increasing contrast (Fig <ref> top and middle). Finally, uncertainty expressed in terms of noise variance should diminish for increasing contrast (Fig <ref> bottom). Indeed, cortical recordings in animals presented with natural visual stimuli, have shown at the neural level how internal models progressively adapt during development to the statistics of natural stimuli, approximating statistically optimal representations as the visual system matures<cit.>. Here we seek to test if standard VAE models, or variations thereof, can capture this behavior and their inference modules be used as models of cortical processing beyond mean responses. We also want to assess and improve the quality of latent uncertainty representations in variational models trained for traditional computer vision tasks.

To that end we audited multiple VAE models with different priors and architectures in a variety of settings in terms of their capacity to represent uncertainty. First, we show that a sparse VAE trained on natural images does not necessarily present all of properties enumerated above. Concretely, we observe an increase in uncertainty with contrast, and no convergence to the prior for zero contrast. In order to fix this behaviour we propose a modification to VAEs, giving rise to the Explaining-Away Variational Autoencoder (EA-VAE). Our model incorporates a global multiplicative latent variable z in the generative model, whose posterior distribution is simultaneously inferred with the traditional latent variables 𝐲 by the encoder (cf. Fig. <ref> left and right). This was inspired by the Gaussian Scale Mixture model (GSM), which has been shown to capture basic statistics of natural image patches <cit.> and has previously been used to explain behavioral and neural data related to both stationary and dynamic responses in visual perception<cit.>. In these models, the simultaneous high activation of a large number of local variables in the VAE can be replaced in a simpler fashion by an increase of a single multiplicative variable. Hence the term explaining-away, in our EA-VAEs. This is closely related to the principle of Occam's razor <cit.> which favors choosing the simpler explanation to two alternative competing hypotheses. We compared our model to classical VAEs in the domain of natural images and other canonical computer vision domains such as handwritten characters<cit.> and x-ray medical images<cit.>. Based on these experiments, we systematically show that, contrary to standard VAEs, our model is able to represent uncertainty in a meaningful and useful fashion.




§ RESULTS




 §.§ Inference on natural images


We started by training a standard sparse VAE on gray-scale square patches of natural images (Methods and Fig <ref>) and compared the resulting model to an EA-VAE trained in the same way. We found that both the  and EA-VAE could be successfully trained on this task, showing a asimilar capacity to reconstruct natural images (Fig <ref>). Delving into the latent layer representations, we found that, as had been shown for the VAE <cit.>, the receptive fields of neurons in the latent layer of EA-VAE also segregated into two types. One subset was composed of units with localized receptive fields, which were sensitive to specific orientations, while the remaining units presented noisy and uninformative filters (Fig <ref>). The system recruits as many units as it needs given the effective dimensionality of the image space (Methods). Importantly, the receptive fields of informative neurons in the EA-VAE resemble those found in primary visual cortex <cit.> when employing a Laplacian (but not a Gaussian) prior, in line with previous reports for VAEs<cit.>, and consistent with classical findings from sparse coding<cit.>.





  §.§.§ Uncertainty representation in the latent space


Next we analysed the properties of the VAE’s posterior representations, by considering them in terms of their signal mean, signal variance, and noise variance (Methods). Given the receptive fields previously shown, we know these latent variables each represent the probability of a given orientation being locally present in a portion of the image. As expected, we found that as contrast increases, and different images become more distinct, the signal mean and signal variance increase as well. This is a result of the centers of individual posteriors separating from the prior and each-other, as expected  (Fig <ref>, left column, top and middle). Surprisingly however, noise variance, encoding the remaining posterior uncertainty about the presence of each orientation, does not decrease with contrast in the VAE (Fig <ref>, left column, bottom). Moreover, as contrast tends to zero, and local orientations become progressively harder to distinguish, uncertainty increasingly deviates from that of the prior. We found that in this case the posterior of a blank image (contrast zero), had a mean noise variance of 0.17, strongly deviating from the unitary variance of prior.




EA-VAE's posteriors also show increasing signal mean and variance as a function of contrast, as the standard VAE. Critically, in contrast to VAEs, EA-VAEs report a decreasing level of uncertainty for higher contrasts. We found low noise variance for high contrast patches, which increases as contrast becomes lower, finally converging to the prior noise variance at zero contrast (Fig <ref>, right column). Indeed, the blank image mean uncertainty has unitary standard deviation, matching the prior in the case of the EA-VAE, but not in the VAE (Cf. Fig <ref>, bottom row).










 §.§ Inference in classical computer vision problems

To explore whether the observed properties of VAEs and EA-VAEs regarding uncertainty representation were unique to the domain of natural images or may extend to other domains, we next studied the MNIST <cit.> handwritten numbers and ChestMNIST <cit.> chest x-rays datasets. Here again both types of models were trained on each dataset and compared in a set of experiments exploring uncertainty in a variety of scenarios.



  §.§.§ Uninformative observations

In the case of MNIST and ChestMNIST, images have standardized contrast, which means we cannot use this variable as a proxy for uncertainty as in the case of natural images. We will instead resort to a number of experimental configurations to show different properties of the proposed model. Firstly, instead of a zero contrast image, we take the pixel-wise average image across the dataset as an uninformative image in order to compare the models. As expected, this image resembles a blurry, unrecognizable digit for MNIST (Fig <ref>) and a slightly blurry x-ray for ChestMNIST (Fig <ref>). When presented with these averaged images, both the VAE and EA-VAE inferred a posterior with mean close to that of the prior(not shown). The differences once again arise when comparing uncertainty estimates. For the VAE trained on MNIST, the average uncertainty, measured as the noise standard deviation of the posterior along latent dimensions, was u__VAE=0.20. This number was comparable with those of the real handwritten digits, and considerably below the unit standard deviation of the prior (Fig <ref>). Notably, in the EA-VAE the average uncertainty for this image was u__EA-VAE=0.47, doubling that of the VAE and halving the distance to that of the prior. While less marked, a similar tendency emerged between the VAE and EA-VAE trained on ChestMNIST (Fig <ref>). Note that the average x-ray image resembles actual data samples more closely than the average digit image, which may explain why the effect is less pronounced.







  §.§.§ Morphing and uncertainty

When dealing with data with categorical labels indicating classes such as digits, one can compare the uncertainty for images belonging to one of the classes with respect to continuously morphed images which lay in between two of them. One would expect minimal uncertainty, that is low noise standard deviation, at the images corresponding to actual digits, and higher noise deviation for the in-between images. We conducted this numerical experiment for each of the 45 pairs of different digits and plotted the uncertainty along the interpolation path looking for its maximum (Fig <ref>). We found that the maximum fell inside a central window of half the interpolation path length in all cases for the EA-VAE; while VAE satisfied this only in 17 cases (38%) (Fig <ref> cf. left and right columns). This result remained consistent when varying the window width (Details on computation and results of this experiment available in the Supporting Information text).




  §.§.§ Image corruption and uncertainty

We next looked at uncertainty representation as x-ray images fromChestMNIST were progressively corrupted, rendering them increasingly uninformative. We did so in two ways: by applying a Gaussian blur (Fig <ref> top) and by adding Gaussian pixel noise (Fig <ref> bottom) (Details on computation in the Supporting Information text). In both cases the EA-VAE reported increasing uncertainty as the image quality deteriorated. This starkly contrasts with the behavior of VAEs, where latent uncertainty remained almost constant at low values even as the original image is no longer recognizable from the corrupted one (cf. orange and green lines, Fig <ref>). 



  §.§.§ Out of distribution detection


Finally, given that the EA-VAE presented a robust improvement in uncertainty representation for uninformative, corrupted and interpolated images within each dataset, we wondered whether it could also help with out-of-distribution detection. Concretely we asked the question of whether models would report particularly high uncertainty values when shown images from a entirely different dataset to that used for training. Using the three previously employed datasets and their corresponding VAE and EA-VAE trained models, we compared internal representations and reported uncertainties for within distribution vs. out of distribution images (Fig <ref>). 

When looking at the models trained with MNIST and tested on ChestMNIST and natural images we observe two important differences between the VAE and the EA-VAE. Firstly, when analyzing the internal representation of the images by projecting the posterior mean back to pixel space using the decoder, we note how the VAE tends to interpret x-ray images and natural images as digits (Fig <ref>). This is not the case with the EA-VAE, which reconstructs blurry images, while also evidencing a marked increase in the reported uncertainty (Fig <ref>). Indeed, the EA-VAE reports uncertainty levels much closer to the prior when presented with out-of-distribution examples (further analysis in the Supporting Information).





§ DISCUSSION


The use of deep learning methods as modelling tools in neuroscience has proven highly effective in recent years <cit.>, and goal driven approaches in particular continue to push boundaries in our understanding of the links between perception and neural responses <cit.>. From a theoretical point of view, the Bayesian framework provides a natural means to study optimal perception in the brain <cit.>. Since exact Bayesian inference is often intractable, two main approaches have consolidated over the years in order to perform approximate inference beyond single point estimates of the posterior: variational inference and sampling-based inference. While uncertainty representation has been studied in the past in recurrent models of the cortex implementing sampling-based inference <cit.>, to our knowledge there is still an important gap when it comes to a frequently used family of variational models, such as VAEs. This is highly relevant given the tendency of deep CNNs to suffer from calibration problems, resulting in inaccurate uncertainty reports <cit.>.

In this work, we went beyond point estimates, and dealt with representations of latent uncertainty in models of perception obtained by variational deep learning methods. Concretely, we studied VAEs both in the context of natural image perception and computer vision. We present substantial evidence that posteriors inferred by VAEs systematically struggle to represent uncertainty in a meaningful way in cases of image corruption, interpolation, and out-of-distribution detection. Motivated by generative models which employ multiplicative variables such as the GSM <cit.>, we incorporated a global scaling latent variable to VAEs. In these models, the simultaneous high activation of a large number of local variables in the VAE can be explained away by an increase in the global multiplicative variable in the EA-VAE. The result of this modification is extremely robust. Results show that EA-VAEs systematically outperform standard VAEs when it comes to uncertainty representations. EA-VAE posteriors tend to more strongly revert to the prior when images become less informative by either corruption or interpolation, and report high uncertainty for out-of distribution examples.

Moreover, as shown in Ref. <cit.>, artificial neural systems optimized for full Bayesian inference beyond point estimates, for models with explaining away variables such as the GSM, result in solutions with mean responses which precisely recover divisive normalization, a canonical computational mechanism in the cortex<cit.>. It is hence possible that as with divisive normalization in the brain, explaining away variables in artificial neural architectures may play an important role in multiple domains. Indeed, although originally motivated by the study of cortical representations for visual perception in the context of natural images, we have shown equally beneficial properties in standard computer vision datasets such as MNIST and ChestMNIST. While further work is required to assess these benefits in other non-visual modalities, we believe EA-VAEs constitute a promising model type for a wide range of scenarios. Inference models which can readily provide a meaningful representation of uncertainty are crucial in a plethora of fields such as the medical domain where optimal information fusion relies on weighing multiple information sources by their relative uncertainties <cit.>.




§ METHODS




 §.§ Variational Autoencoders


To obtain approximate solutions to the process of Bayesian probabilistic inference, we trained VAEs to simultaneously learn the generative model through a decoder, and the inference model through an encoder.
For any input 𝐱∈ℝ^M, the encoder outputs a variational approximation of the posterior p(𝐲|𝐱) through q_ϕ(𝐲|𝐱), where 𝐲∈ℝ^D is the vector of latent features with an assumed prior p(𝐲). After taking a sample 𝐲 from q_ϕ(𝐲|𝐱), an output 𝐱̂ is reconstructed through the decoder by the approximate likelihood p_φ(𝐱|𝐲) (Fig <ref> left).

The objective function for learning the parameters of the encoder and decoder is given by the Evidence Lower Bound (ELBO)<cit.>. This takes the form:


    ℒ_VAE(𝐱,φ,ϕ) = -𝔼_q_ϕ(𝐲|𝐱)[ log p_φ(𝐱|𝐲)] 
     + β_1 D_KL(q_ϕ(𝐲|𝐱)||p(𝐲))


where the first term expresses the reconstruction error, and a second term acts as regularization, penalising differences between the prior distribution and the learnt approximate posterior of the latent variables.
The β_1 hyperparameter determines the prior regularization weight.



 §.§ Explaining-away VAE

The EA-VAE incorporates to the standard VAE a multiplicative scalar latent variable z∈ℝ, independent from the latent variables 𝐲. That is, any observation 𝐱 is now assumed to have been generated by combining spatial a set of latent features 𝐲 via a function 𝐟(𝐲), further multiplied by a scalar variable z, and corrupted by additive white noise η:



    𝐱 = z  𝐟(𝐲) + η.


Therefore, for an input 𝐱, two separate encoders parameterize the inference process through the approximate posteriors q_ϕ(𝐲|𝐱) and q_ψ
(z|𝐱). For reconstruction, both 𝐲 and z are sampled from their respective posteriors before decoding. Note that 𝐟 is analogous to the decoder from the classic VAE architecture. The difference is that in the EA-VAE, 𝐟(𝐲) is further multiplied by z before being corrupted by noise, obtaining the reconstructed output 𝐱̂ (Fig <ref> right).

Since 𝐲 and z are independent random variables, we write the objective function for the EA-VAE as:


    ℒ_EA-VAE(𝐱,φ,ϕ) = -𝔼_q_ϕ(𝐲|𝐱)[ log p_φ(𝐱|𝐲,z)] 
     + β_1 D_KL(q_ϕ(𝐲|𝐱)||p(𝐲))
     +β_2 D_KL(q_ψ(z|𝐱)||p(z)).




 §.§ Trained models



  §.§.§ VAEs and EA-VAEs for inference on natural images




In this work we focus on inference over gray-scale images. That is, the input 𝐱 corresponds here to a vector of intensity values for each of the pixels in an image. We first implemented and trained a Sparse VAE <cit.> identical to the one described in <cit.> (Fig <ref>). In order to foster sparsity, this model employs multivariate uncorrelated Laplace distributions to parameterize the posteriors: q_ϕ(𝐲|𝐱) = Laplace(𝐲;μ^(𝐱),σ^2(𝐱)), with μ^(𝐱) and σ^2(𝐱) the respective mean and variance vectors. These vectors are computed through the encoder for each specific image 𝐱. The latent prior p(𝐲)
is defined from the same family, with zero mean and unit variance for all spatial latent dimensions. The likelihood for a given x is parameterized by a multivariate uncorrelated Normal distribution p_φ(𝐱|𝐲) = 𝒩(𝐱;Dec(𝐱),η^2)
with Dec(𝐱) the mean (computed as the decoder output); and η^2 the variance (equal for all images).
Thus, Eq. <ref> takes the form of


    ℒ_VAE(𝐱,φ,ϕ) =  ∑_i=1^M(x̂_i-x_i)^2 
    
     + β_1 ∑_j=1^D(-1+|μ^(𝐱)_j|-log(σ^(𝐱)_j/√(2))+σ^(𝐱)_j/√(2)e^-√(2)|μ^(𝐱)_j|/σ^(𝐱)_j)


The EA-VAE preserves the previous architecture but incorporates a scalar multiplicative latent variable z. For natural images patches, this variable is drawn from a Gamma distribution and represents in our model the contrast of the patch, as in previous work modelling natural image patches employing GSMs<cit.> (Fig <ref>). A Gamma distribution can be parametrized in terms of the shape and scale parameters k and θ respectively. Here we have assumed for simplicity that all posteriors  q_ψ(z|𝐱)=Gamma(z;k,θ^(𝐱)) have a fixed shape parameter k=2. Moreover, the proposed model infers the scale parameter for each image from the across-pixel standard deviation of intensities in 𝐱: σ_pix^(𝐱). Since k is fixed, the posterior's mean, mode and variance depend only on the inferred scale parameter θ. For the prior distribution, the shape parameter was also fixed at k=2 and the scale parameter θ=1/√(2) was chosen such that the prior had unit variance s^2=kθ^2=1. k=2 was chosen as the smallest integer number that qualitatively achieved a similar distribution to the dataset's σ_pix distribution. Computationally, the choice of a fixed integer k, simplifies the sampling procedure, since one can always sample from the same standard Gamma function and then reparametrize by the scale parameter. This enables simple gradient computations across the sampling process. Furthermore, a constant shape parameter k means that the posterior standard deviation is always proportional to the posterior mean. This satisfies Weber's Law of perception<cit.>, where the estimation error of a quantity is constant fraction of its mean.
Under these assumptions, Eq.<ref> can be expressed as

    ℒ_EA-VAE(𝐱,φ,ϕ) =    ∑_i=1^M(x̂_i-x_i)^2 
     + β_1 ∑_j=1^D(-1+|μ^(𝐱)_j|-log(σ^(𝐱)_j/√(2))+σ^(𝐱)_j/√(2)e^-√(2)|μ^(𝐱)_j|/σ^(𝐱)_j) 
       + β_2 2(-log√(2)-logθ^(𝐱)+√(2) θ^(𝐱)-1),





  §.§.§ VAEs and EA-VAEs for handwritten characters and medical images

In contrast to the natural image models, the models trained on MNIST handwritten digits dataset and ChestMNIST x-ray images consist of an encoder and decoder composed by both fully-connected and convolutional layers (Fig <ref> and <ref>). Moreover, as is more standard in the ML field, the inferred posteriors are parameterised as Multivariate uncorrelated Normal distributions  q_ϕ(𝐲|𝐱) = Normal(𝐲;μ^(𝐱),σ^2(𝐱)), with μ^(𝐱) and σ^2(𝐱) the respective mean and variance vectors. In the case of the EA-VAE we also have a multiplicative z latent viariable, whose posterior is given by q_ψ(z|𝐱) = Normal(z;ν^(𝐱),ξ^2(𝐱)). Priors p(𝐲) and p(z) come from the same family as their respective posteriors but with zero mean and diagonal unit covariance. As before, the likelihood function assumes uncorrelated normally distributed noise.



 §.§ Datasets



  §.§.§ Inference on Natural Images

We used the same dataset as in <cit.>, composed of natural image patches of 40×40 pixels each<cit.> (6.4×10^5 images for training and validation and 6.4×10^4 for test). The first set was further divided into 80% for training and 20% for validation purposes. Image patches already had already been preprocessed, whereby 100(1 - π/4)% of the higher frequency PCA components had been discarded. By means of this filtering, the effective dimensionality of the image space had been reduced to 1256. Note that the patch size remains unaltered. Additionally, the distribution of pixel intensities was rescaled such that it's mean ± 3 deviations fit the range [0,1], to have the same range for all domains. This was important for the out-of-distribution evaluations. Finally, the mean pixel intensity of each patch was subtracted before the image enters the encoder network. 



  §.§.§ Inference on the MNIST and ChestMNIST datasets

VAEs and EA-VAEs were trained using the handwritten numbers MNIST<cit.> and x-ray images ChestMNIST<cit.> datasets separately.

Each original 28×28 pixel image was resized to 32×32 due to the 3 layered convolutional encoder and decoder architecture, and the pixel intensity distribution of the whole dataset was rescaled to fit the range [0,1].



§ ACKNOWLEDGMENTS

This work was supported by Argentina’s National Scientific and Technical Research Council (CONICET), which covered the salaries of all the authors. The authors gratefully acknowledge NVIDIA Corporation for the GPU computing, and the support of Universidad Nacional del Litoral (Grants CAID-PIC-50220140100084LI, 50620190100145LI), ANPCyT (PICT-PRH-2019-00009, 2022-03-00593).


unsrt  
  





§ SUPPORTING INFORMATION



 §.§ Models' training

All models were trained in Python 3.11.3 with Pytorch 2.0.1 on a GPU NVIDIA TITAN V. A 64GB RAM memory was available during training. An Adam optimizar was used with a learning rate of 10^-3 and weight decay of 10^-5. The fitting step was done each time a batch of size 128 passed through the network.



  §.§.§ VAE and EA-VAE trained with van Hateren


β_1 hyperparameter was fixed exploratorily such that the decoder's reconstructions did not present visibly strong deviations from the original input. The selected choice was of β_1=0.015 and β_2=0.1 for the VAE and EA-VAE trained on patches of natural images. Results are robust with respect to changes in these hyperparameters, with no abrupt qualitative changes.



The models were trained for 10000 epochs, and early stopping was employed so that the parameters were finally set at the epoch with best performance on the validation images. As a reference, the time taken to achieve each respective best epoch in this setting was of 62.2 hours for the VAE vs 67 hours for the EA-VAE. That is, the improvement in uncertainty representation in the EA-VAE comes at an expense of roughly an additional 10% computational time.



  §.§.§ VAEs and EA-VAEs trained with MNIST and ChestMNIST

The regularization hyperparameters were set to β_1=5 and β_2=1 for networks trained with MNIST dataset, and of β_1=1 and β_2=1 for the networks trained with ChestMNIST.

Although the EA-VAE has 24% more parameters than the VAE, all models took around one hour to complete the 500 epochs. The final model parameters were set to the epoch that achieved the lowest cost function on the validation set. We note that the use of convolutions in this case drastically reduces training times from the case of natural images employing all fully connected layers.



 §.§ Evaluation of VAEs and EA-VAEs trained on van Hateren




  §.§.§ Latent receptive fields

The receptive field 𝐅_j associated to the j-th latent dimension was computed through the Spike Triggered Average (STA) technique on the test dataset for all j=1,...,1800. The STA was estimated as:

    𝐅_j =  {𝐱}mean μ_j^(𝐱)𝐱

where μ_j^(𝐱) is the j-th component of the mean of 𝐱's inferred posterior q_ϕ(𝐲|𝐱).

Latent units were discerned as informative or non-informative according to their contribution to the dataset reconstruction. When computing the relative change in the images reconstructed when all units are active, or when a specific unit is replaced by its mean activation throughout the ensemble, it is seen that the units associated to orientation-sensitive filters are clustered with the most contribution, while the second group barely contribute. All results shown in the main text were computed using only the informative latent dimensions.



  §.§.§ Uncertainty representation in the latent space


We quantified the response of neurons for different observations and levels of uncertainty through the signal mean, signal variance and noise variance as a function of contrast z.
For this, given an ensemble of patches {𝐱}, we start by inferring a contrast z^*(𝐱) for each patch. In the case of the VAE, we infer contrast as the across-pixel standard deviation of intensities: z^*(𝐱)__VAE = σ_pix^(𝐱), while for the EA-VAE model we use the encoded mean of the inferred posterior distribution of z as contrast: z^*(𝐱)__EA-VAE = kθ^(𝐱)

The signal mean is defined as the average distance of the posterior's mean to the prior's mean (0 in this case) over all patches that have the same inferred contrast z:

    SM(z) = {𝐱 | z^*(𝐱)=z }meanμ^(𝐱)


Signal variance is computed as the variance of the posterior's mean of patches of same contrast, averaged across latent dimensions:

    SV(z) = jmean{𝐱 | z^*(𝐱)=z }Varμ_j^(𝐱)


Finally, noise variance is defined as the posterior's variance vector σ^2(𝐱) averaged across latent dimensions and observations of equal inferred contrast z:

    NV(z) = jmean{𝐱 | z^*(𝐱)=z }meanσ_j^2(𝐱)


These quantities were computed for the test set, where no two patches have the same exact contrast. Hence, these were binarized with small enough bins such that no jumps were visible in the plots, and with error bars comparable to line-widths. The binnarized expressions are as follows:

    SM(z_i) = {𝐱 | z^*(𝐱)∈ B_i }meanμ^(𝐱)


    SV(z_i) = jmean{𝐱 | z^*(𝐱)∈ B_i }Varμ_j^(𝐱)


    NV(z_i) = jmean{𝐱 | z^*(𝐱)∈ B_i }meanσ_j^2(𝐱)


The associated errors can be expressed as:

    ϵ__SM(z_i)=1/√(N_i)√({𝐱|z^*(𝐱)∈ B_i}Varμ^(𝐱))


    ϵ__SV(z_i)=1/√(D)jmean√(2/(N_i-1)){𝐱|z^*(𝐱)∈ B_i}Varμ_j^(𝐱)


    ϵ__NV(z_i)=1/√(N_i)√(D)√({j∪𝐱|z^*(𝐱)∈ B_i}Varσ^2(𝐱))


Moreover, we selected the specific subset of patches with σ_pix^(𝐱)=1 and computed these quantities for them and for copies of this images but synthetically modifying their contrast. The resulting moments had the same behaviour as the ones found with the whole test set with original contrast values.







It is worth mentioning that the natural scenes dataset used in this work has patches with varied values of pixel intensity standard deviation z_pix^(𝐱). As patches with high contrast live far away from the origin in the in the N-dimensional pixel space (since z_pix^(𝐱) = √(1/N-1∑_i=1^N(x_i-x̅)^2) = √(1/N-1)𝐱), it is expected that the network will have more difficulty exploring farther regions in the pixel space than the regions where low-contrast patches live. Therefore, in evaluation instances, patches with contrast higher than σ_pix=1 were discarded.











 §.§ Evaluation of VAEs and EA-VAEs trained on MNIST and ChestMNIST



  §.§.§ Morphing and uncertainty

We conducted an experiment to study the uncertainty in the VAE and EA-VAE latent space when morphing digits from one label to another.
The first step for doing this was selecting all the test images that belong to a specific label A and computing the average coordinate in the latent space of these (Fig <ref>a top panels). The output 𝐱̂_A of the decoder from that position is a representative image of the label A (Fig <ref>a bottom). The same procedure is repeated with images belonging to label B obtaining 𝐱̂_B. Then, morphing is done by linearly combining 𝐱̂_A and 𝐱̂_B with weight λ varying from 0 to 1:

    𝐱̂_AB,λ=(1-λ) 𝐱̂_A + λ𝐱̂_B


We then inferred the corresponding posteriors taking these morphed images as input, and computed the uncertainty of the network as the standard deviations of the posterior averaged across latent dimensions:

    noise std.(λ;AB)=jmean  σ_j^(𝐱̂_AB,λ)

Through this procedure, uncertainty curves were computed for all the combinations of morphing from labels 0 to 9 (Fig <ref>c black curves).

To evaluate if a certain curve has the expected behaviour of being maximally uncertain at intermediate λ values, we fitted a second order polynomial function (Fig <ref>c red curves) and checked whether it's curvature was negative and the maximum was located inside a window of size L centered respect to λ=0.5, for different L values (Fig <ref>b). 



  §.§.§ Image corruption

The image corruption experiment was done over the complete test set.
Each image was synthetically corrupted by applying a two-dimensional Gaussian kernel of covariance η_b I_2x2. The resulting blurred image was encoded into the models' latent space, where the measure of uncertainty was computed. We compute the uncertainty of the network for a given input 𝐱 as the standard deviations of the posterior q_ϕ(𝐲|𝐱) averaged across latent dimensions:

    noise std.=jmean  σ_j^(𝐱)

This process was repeated for all images, and the average uncertainty was computed. This was repeated for different η_b values until the images were completely blurred out (η_b=16 equal to half the pixel width of the images)
We repeated the experiment with pixel-noise corruption. In this case each pixel was intensity corrupted by additive white Gaussian noise of null mean and variance η_p^2. The whole perturbed image was then rescaled in intensity to preserve the original range of intensities.η_p values between 0 and 5 were considered, going from no perturbation to a strongly perturbed image.


  §.§.§ Out of distribution experients

To study the capacity of the trained models to associate near-to-prior uncertainty for images from previously unseen distributions, we compared the latent representations of images in and out of the distribution used for training. We computed the uncertainty of the network to a given observation the same way as in the two previous experiments.
We looked at: (1) models trained with MNIST and tested on ChestMNIST and natural images (Fig <ref> on main text); (2) models trained with ChestMNIST and tested on MNIST and natural images (Fig <ref>); and (3) models trained with natural images and tested on MNIST and ChestMNIST (Fig <ref>).
In all three cases, images from the out of distribution datasets were resized to coincide the size of images from the training set, and rescaled in pixel intensity to match the in-distribution pixel intensity distribution.

We found the same behaviour as shown in the main text when training models with x-ray images and testing on natural images (Fig <ref>, rightmost block). Yet when testing on digits, both models seem to fare comparably, with reported uncertainties that do not approach the prior, although the reconstructed images do not collapse to within domain examples.
When training with natural images and testing on the other two (Fig <ref>), the distribution of reported uncertainties, which originally had two modes for within distribution images corresponding to more informative (high contrast) and less informative (low contrast) images, reduces to a single mode mode for VAEs and EA-VAEs. The asymmetry in the results when original and target domains are inverted suggests a hierarchy in the richness of the feature space learned from the statistics of the images.







