swa_gaussian
Code repo for "A Simple Baseline for Bayesian Uncertainty in Deep Learning"
view repo
We propose SWA-Gaussian (SWAG), a simple, scalable, and general purpose approach for uncertainty representation and calibration in deep learning. Stochastic Weight Averaging (SWA), which computes the first moment of stochastic gradient descent (SGD) iterates with a modified learning rate schedule, has recently been shown to improve generalization in deep learning. With SWAG, we fit a Gaussian using the SWA solution as the first moment and a low rank plus diagonal covariance also derived from the SGD iterates, forming an approximate posterior distribution over neural network weights; we then sample from this Gaussian distribution to perform Bayesian model averaging. We empirically find that SWAG approximates the shape of the true posterior, in accordance with results describing the stationary distribution of SGD iterates. Moreover, we demonstrate that SWAG performs well on a wide variety of computer vision tasks, including out of sample detection, calibration, and transfer learning, in comparison to many popular alternatives including MC dropout, KFAC Laplace, and temperature scaling.
READ FULL TEXT VIEW PDFCode repo for "A Simple Baseline for Bayesian Uncertainty in Deep Learning"
None
None
None
Studies of the article : https://arxiv.org/abs/1902.02476
Ultimately, machine learning models are used to make decisions. Representing uncertainty is crucial for decision making. For example, in medical diagnoses and autonomous vehicles we want to protect against rare but costly mistakes. Deep learning models typically lack a representation of uncertainty, and provide overconfident and miscalibrated predictions (e.g., Kendall & Gal, 2017; Guo et al., 2017).
Bayesian methods provide a natural probabilistic representation of uncertainty in deep learning (e.g., Blundell et al., 2015; Kingma et al., 2015b; Chen et al., 2014), and previously had been a gold standard for inference with neural networks (Neal, 1996)
. However, existing approaches are often highly sensitive to hyperparameter choices, and hard to scale to modern datasets and architectures, which limits their general applicability in modern deep learning.
In this paper we propose a different approach to Bayesian deep learning: we use the information contained in the SGD trajectory to efficiently approximate the posterior distribution over the weights of the neural network. We find that the Gaussian distribution fitted to the first two moments of SGD iterates, with a modified learning rate schedule, captures the local geometry of the posterior surprisingly well. Using this Gaussian distribution we are able to obtain convenient, efficient, accurate and well-calibrated predictions in a broad range of tasks in computer vision. In particular, our contributions are the following:
In this work we propose SWAG (SWA-Gaussian), a scalable approximate Bayesian inference technique for deep learning. SWAG builds on Stochastic Weight Averaging
(Izmailov et al., 2018), which computes an average of SGD iterates with a high constant learning rate schedule, to provide improved generalization in deep learning. SWAG additionally computes a low-rank plus diagonal approximation to the covariance of the iterates, which is used together with the SWA mean, to define a Gaussian posterior approximation over neural network weights.SWAG is motivated by the theoretical analysis of the stationary distribution of SGD iterates (e.g., Mandt et al., 2017; Chen et al., 2016), which suggests that the SGD trajectory contains useful information about the geometry of the posterior. In Section 4 we show that the assumptions of Mandt et al. (2017) do not hold for deep neural networks, due to non-convexity and over-parameterization. However, we find that in the subspace spanned by SGD iterates the shape of the posterior distribution is approximately Gaussian. Further, SWAG is able to capture the geometry of this posterior remarkably well.
On a thorough empirical evaluation we show that SWAG can provide well-calibrated uncertainty estimates for neural networks across many settings in computer vision. In particular SWAG achieves higher test likelihood compared to many state-of-the-art approaches, including MC-Dropout
(Gal & Ghahramani, 2016), temperature scaling (Guo et al., 2017), KFAC-Laplace (Ritter et al., 2018b) and SWA (Izmailov et al., 2018)on CIFAR-10, CIFAR-100 and ImageNet, on a range of architectures. We also demonstrate the effectiveness of SWAG for out-of-domain detection, and transfer learning.
Bayesian approaches represent uncertainty by placing a distribution over model parameters, and then marginalizing these parameters to form a whole predictive distribution, in a procedure known as Bayesian model averaging. In the late 1990s, Bayesian methods were the state-of-the-art approach to learning with neural networks, through the seminal works of Neal (1996) and MacKay (1992a). However, modern neural networks often contain millions of parameters, the posterior over these parameters (and thus the loss surface) is highly non-convex, and mini-batch approaches are often needed to move to a space of good solutions (Keskar et al., 2017). For these reasons, Bayesian approaches have largely been intractable for modern neural networks. Here, we review several modern approaches to Bayesian deep learning.
was at one time a gold standard for inference with neural networks, through the Hamiltonian Monte Carlo (HMC) work of Neal (1996). However, HMC requires full gradients, which is computationally intractable for modern neural networks. To extend the HMC framework, stochastic gradient HMC (SGHMC) was introduced by Chen et al. (2014) and allows for stochastic gradients to be used in Bayesian inference, crucial for both scalability and exploring a space of solutions that provide good generalization. While SGHMC has been successfully applied in Bayesian deep learning (e.g., Saatci & Wilson, 2017), tuning SGHMC can be quite difficult, and many settings of SGHMC parameters are quite similar to standard SGD.
Graves (2011) suggested fitting a Gaussian variational posterior approximation over the weights of neural networks. This technique was generalized by Kingma & Welling (2013) which proposed the reparameterization trick for training deep latent variable models; multiple variational inference methods based on reparameterization trick were proposed for DNNs (e.g., Kingma et al., 2015a; Blundell et al., 2015; Molchanov et al., 2017; Louizos & Welling, 2017). While variational methods achieve strong performance for moderately sized networks, they can be difficult to train on larger architectures such as deep residual networks (He et al., 2016), due to the looseness of the optimization objective by Blier & Ollivier (2018).
Gal & Ghahramani (2016) used a spike and slab variational distribution to view dropout at test time as approximate variational Bayesian inference. Concrete dropout (Gal et al., 2017)
extends this idea to optimize the dropout probabilities as well. From a practical perspective, these approaches are quite appealing as they only require ensembling dropout predictions at test time, and they were succesfully applied to several downstream tasks
(Kendall & Gal, 2017; Mukhoti & Gal, 2018).assume a Gaussian posterior, where is a MAP estimate and is the inverse of the Fisher information matrix (expected value of the Hessian evaluated at ). It was notably used for Bayesian neural networks in MacKay (1992b), where a diagonal approximation to the inverse of the Hessian was utilized for computational reasons. More recently, Kirkpatrick et al. (2017) proposed to use diagonal Laplace approximations to overcome catastrophic forgetting in deep learning. Ritter et al. (2018b) proposed the use of either a diagonal or block Kronecker factored (KFAC) approximation to the Hessian matrix for Laplace approximations, and Ritter et al. (2018a) successfully applied the KFAC approach to online learning situations.
Alternatively, Lakshminarayanan et al. (2017)
proposed using ensembles of several networks for enhanced calibration, and incorporated an adversarial loss function to be used when possible as well. Outside of probabilistic neural networks,
Guo et al. (2017)proposed temperature scaling, a procedure which uses a validation set and a single hyperparameter to rescale the logits of DNN outputs for enhanced calibration.
Kuleshov et al. (2018) propose calibrated regression using a similar rescaling technique.In this section we propose SWA-Gaussian (SWAG) for Bayesian model averaging and uncertainty estimation. In Section 3.1, we review stochastic weight averaging (SWA) (Izmailov et al., 2018), which we view as estimating the mean of the stationary distribution of SGD iterates. We then propose SWA-Gaussian in Sections 3.2 and 3.3 to estimate the covariance of the stationary distribution, forming a Gaussian approximation to the posterior over weight parameters. With SWAG, uncertainty in weight space is captured with minimal modifications to the SWA training procedure. We then present further theoretical and empirical analysis for SWAG in Section 4.
The main idea of SWA (Izmailov et al., 2018)
is to run SGD with a constant learning rate schedule starting from a pre-trained solution, and to average the weights of the models it traverses. Denoting the weights of the network obtained after epoch
of SWA training the SWA solution after epochs is given by A high constant learning rate schedule ensures that SGD explores the set of possible solutions instead of simply converging to a single point in the weight space. Izmailov et al. (2018) argue that conventional SGD training converges to the boundary of the set of high-performing solutions; SWA on the other hand is able to find a more centered solution that is robust to the shift between train and test distributions, leading to improved generalization performance. SWA and related ideas have been successfully applied to a wide range of applications (see e.g. Athiwaratkun et al., 2019; Yazici et al., 2019; Nikishin et al., 2018).A related but different procedure is Polyak-Ruppert averaging Polyak & Juditsky (1992); Ruppert (1988) in stochastic convex optimization, which uses a learning rate decaying to zero. Burn-in periods and thinning are known to accelerate the convergence speed of Polyak-Ruppert averaging (Rakhlin et al., 2011), which provides some evidence for the effectiveness of SWA in practice.
We first consider a simple diagonal format for the covariance matrix. Diagonal covariance matrices are standard for variational inference and Laplace approximations in Bayesian deep learning (e.g., Blundell et al., 2015; Kirkpatrick et al., 2017). In order to fit a diagonal covariance approximation, we maintain a running average of the second uncentered moment for each weight, and then compute the covariance using the following standard identity at the end of training:
where the squares in and are applied elementwise. The resulting approximate posterior distribution is then In our experiments, we term this method SWAG-Diagonal.
Constructing the SWAG-Diagonal posterior approximation requires storing two additional copies of DNN weights: and . Note that these models do not have to be stored on the GPU. The additional computational complexity of constructing SWAG-Diagonal compared to standard training is negligible, as it only requires updating the running averages of weights once per epoch.
While the diagonal covariance approximation is standard in Bayesian deep learning, it can be too restrictive. We extend the idea of SWAG-Diagonal to use a more flexible low-rank plus diagonal form of the approximate covariance.
Note that the sample covariance matrix can be written as the sum of outer products, , and is of rank . As we do not have access to the value of during training, we approximate the sample covariance with where is the deviation matrix comprised of columns and is the running estimate of the parameters’ mean obtained from the first samples. In practice to limit the rank of the estimated covariance matrix we only use the last of vectors corresponding to the last epochs of training. Here is the rank of the resulting approximation and is a hyperparameter of the method. We define to be the matrix with columns equal to for .
We then combine the resulting low-rank approximation with the diagonal approximation of section 3.2. The resulting approximate posterior distribution is a Gaussian with the SWA mean and summed covariance: .^{1}^{1}1
We use one half as the scale here because both the diagonal and low rank terms include the variance of the weights. We tested several other scales in Appendix
C. In our experiments, we term this method SWAG. Computing this approximate posterior distribution requires storing vectors of the same size as the model as well as the vectors and . These models do not have to be stored on a GPU.Related methods for estimating the covariance of SGD iterates were considered in Mandt et al. (2017) and Chen et al. (2016), but store full-rank covariance and thus scale quadratically in the number of parameters, which is prohibitively expensive for deep learning applications. We additionally note that using the deviation matrix for online covariance matrix estimation comes from viewing the online updates used in Dasgupta & Hsu (2007) in matrix fashion.
We sample from SWAG-diagonal by taking
where is the number of parameters in the network. Note that is diagonal, and the product can be computed in time. Similarly, to sample from SWAG we use the following identity
(1) | |||
In both cases, Bayesian predictions on the testing data, using the approximate posterior, , can now be made using Bayesian model averaging:
where can be either the SWAG or SWAG-diagonal approximate posterior distribution, and is the number of samples. The full Bayesian model averaging procedure for SWAG is described in Algorithm 1. We note that like Izmailov et al. (2018)
(SWA) we update the batch normalization statistics after sampling weights for models that use batch normalization
(Ioffe & Szegedy, 2015); an investigation into the necessity of this update is in Appendix C.4.Maximum a-posteriori (MAP) optimization is a procedure whereby one maximizes the (log) posterior with respect to parameters :
(2) |
Here, the prior is viewed as a regularizer in optimization. However, MAP is not Bayesian inference, since one only considers a single setting of the parameters in making predictions, forming , where and are test inputs and outputs.
A Bayesian procedure instead marginalizes the posterior distribution over , in a Bayesian model average, for the unconditional predictive distribution:
(3) |
In practice, this integral is computed through a Monte Carlo sampling procedure:
(4) |
We emphasize that we are performing full Bayesian inference, rather than MAP optimization. We develop a Gaussian approximation to the posterior from SGD iterates, , and then sample from this posterior distribution to perform a Bayesian model average. In our procedure, optimization with different regularizers, to characterize the Gaussian posterior approximation, corresponds to fully Bayesian inference with different priors .
Typically, weight decay is used to regularize DNNs, corresponding to explicit L2 regularization when SGD without momentum is used to train the model. When SGD is used with momentum, as is typically the case, implicit regularization still occurs, producing a vague prior on the weights of the DNN in our procedure. This regularizer can be given an explicit Gaussian-like form (see Proposition 3 of Loshchilov & Hutter (2019)), corresponding to a prior distribution on the weights. Thus, SWAG is an approximate Bayesian inference algorithm in our experiments (see Section 5) and can be applied to most DNNs without any modifications of the training procedure (as long as SGD is used with weight decay or explicit L2 regularization). Alternative regularization techniques could also be used, producing different priors on the weights.
Posterior joint density cross-sections along the rays corresponding to different eigenvectors of SWAG covariance matrix.
Middle:Posterior joint density surface in the plane spanned by eigenvectors of SWAG covariance matrix corresponding to the first and second largest eigenvalues and (
Right:) the third and fourth largest eigenvalues. All plots are produced using PreResNet-164 on CIFAR-100. The SWAG distribution projected onto these directions fits the geometry of the posterior density remarkably well.Standard training of deep neural networks (DNNs) proceeds by applying stochastic gradient descent on the model weights with the following update rule:
where the learning rate is the th input (e.g. image) and label are , the size of the whole training set is , the size of the batch is , and the DNN, has weight parameters .^{2}^{2}2We ignore momentum for simplicity in this update; however the following theoretical results can be extended to include momentum. The loss function is a negative log likelihood combined with a regularizer . This type of maximum likelihood training does not represent uncertainty in the predictions or parameters .
Under conditions of decaying learning rates, smoothness of gradients, and the existence of a full rank stationary distribution, martingale based analyses of stochastic gradient descent (e.g., Asmussen & Glynn, 2007, Chapter 8) show that SGD has a Gaussian limiting distribution. That is, in the infinite time step limit, where is some covariance matrix and is a stationary point or minima. Mandt et al. (2017), and Chen et al. (2016) are additional examples of this style of analysis. We focus on the assumptions of Mandt et al. (2017)
in the next section. We note that these are essentially the same conditions as for the Bernstein von Mises Theorem
(e.g., Vaart, 1998, Chapter 10) which shows that the asymptotic posterior will also be Gaussian asymptotically.In this section, we investigate the results of Mandt et al. (2017) in the context of deep learning. Mandt et al. (2017) uses the following assumptions:
Gradient noise at each point is .
is independent of and full rank.
The learning rates, are small enough that we can approximate the dynamics of SGD by a continuous-time dynamic described by the corresponding stochastic differential equation.
In the stationary distribution, the loss is approximately quadratic near the optima, i.e. approximately where is the Hessian at the optimum; further, the Hessian is assumed to be positive definite.
Assumption 1 is motivated by the central limit theorem, and Assumption 3 is necessary for the analysis in
Mandt et al. (2017). Assumptions 2 and 4 may or may not hold for deep neural networks (as well as other models). Under these assumptions, Theorem 1 of Mandt et al. (2017) derives the optimal constant learning rate that minimizes the KL-divergence between the SGD stationary distribution and the posterior^{3}^{3}3An optimal diagonal preconditioner is also derived; our empirical work applies to that setting as well. A similar analysis with momentum holds as well, adding in only the momentum coefficient.:(5) |
where is the size of the dataset, is the dimension of the model, is the minibatch size and is the gradient noise covariance.
We computed Equation 5 over the course of training for two neural networks in Figure A.3(a), finding that the predicted optimal learning rate was orders of magnitude larger than what would be used in practice to explore the loss surface in a reasonable time (about compared to ). See Appendix A for further details.
We now focus on seeing how Assumptions 2 and 4 fail for DNNs; this will give further insight into what portions of the theory do hold, and may give insights into a corrected version of the optimal learning rate.
In Figure A.3(b), the trace of the gradient noise covariance and thus the optimal learning rates are nearly constant; however, the total variance is much too small to induce effective learning rates, probably due to over-parameterization effects inducing non full rank gradient covariances as was found in Chaudhari & Soatto (2018). We note that this experiment is not sufficient to be fully confident that is independent of the parameterization near the local optima, but rather that is close to constant; further experiments in this vein are necessary to test if the diagonals of are constant. The result that is close to constant suggests that a constant learning rate could be used for sampling in a stationary phase of training. The dimensionality parameter in Equation 5 could be modified to use the number of effective parameters or the rank of the gradient noise to reduce the optimal learning rate to a feasible number.
To test assumption 4, we used a GPU-enabled Lanczos method from GPyTorch (Gardner et al., 2018) and used restarting to compute the minimum eigenvalue of the train loss of a pre-trained PreResNet-164 on CIFAR-100. We found that even at the end of training, the minimum eigenvalue was (the maximum eigenvalue was for comparison), indicating that the Hessian is not positive definite. This result harmonizes with other work analyzing the spectra of the Hessian for DNN training (Li et al., 2018; Sagun et al., 2018). Further, Garipov et al. (2018) and Draxler et al. (2018) argue that the loss surfaces of DNNs have directions along which the loss is completely flat, suggesting that the loss is nowhere near a positive-definite quadratic form.
As we have seen in Section 4.2, the theoretical results of Mandt et al. (2017) may not directly apply to DNNs. This is slightly different from our intuition about the problem; we expect the SGD trajectory to contain information about the shape of the loss surface (and thus also the posterior distribution), because the loss surface informs how we step from one point to the next. In this section we empirically verify that SWAG can capture the local geometry of the posterior distribution.
In order to analyze the quality of the SWAG approximation, we study the posterior density along the directions corresponding to the eigenvectors of the SWAG covariance matrix for PreResNet-164 on CIFAR-100. In order to find these eigenvectors we use randomized SVD (Halko et al., 2011).^{4}^{4}4From sklearn.decomposition.TruncatedSVD. In the left panel of Figure 1 we visualize the -regularized cross-entropy loss (equivalent to the joint density of the weights and the loss with a Gaussian prior) as a function of distance from the SWA solution along the -th eigenvector of the SWAG covariance:
As we can see in the left panel of Figure 1, there is a clear correlation between the variance of the SWAG approximation and the width of the posterior along the directions . The SGD iterates indeed contain useful information about the shape of the posterior distribution, and SWAG is able to capture this information. We repeated the same experiment for SWAG-Diagonal, finding that there was almost no variance in these eigen-directions. Next, we plot the posterior density surface in the 2-dimensional plane in the weight space spanning the two top eigenvectors and of the SWAG covariance
We plot the results in the middle panel of Figure 1. Again, we can see that SWAG is able to capture the geometry of the posterior. The contours of constant posterior density appear to be remarkably well aligned with the eigenvalues of the SWAG covariance. We also present the analogous plot for the third and fourth top eigenvectors in the right panel of Figure 1. In Appendix B, we additionally present similar results for PreResNet-164 on CIFAR-10 and VGG-16 on CIFAR-100.
As we can see, SWAG is able to capture the geometry of the posterior in the subspace spanned by SGD iterates. However, the dimensionality of this subspace is very low compared to the dimensionality of the weight space, and we can not guarantee that SWAG variance estimates are adequate along all directions in weight space. In particular, we would expect SWAG to under-estimate the variances along random directions, as the SGD trajectory is in a low-dimensional subspace of the weight space, and a random vector has a close-to-zero projection on this subspace with high probability.
We conduct a thorough empirical evaluation of SWAG, comparing to a range of high performing baselines, including MC dropout (Gal & Ghahramani, 2016), temperature scaling (Guo et al., 2017), and Laplace approximations (Ritter et al., 2018b). In Section 5.1 we evaluate SWAG predictions and uncertainty estimates on image classification tasks. We also evaluate SWAG for transfer learning and out-of-domain data detection. We present experiments investigating the effect of hyperparameter choices and practical limitations in SWAG in Appendix C.
In this section we evaluate the quality of uncertainty estimates as well as predictive accuracy for SWAG and SWAG-Diagonal and baselines on CIFAR-10, CIFAR-100 and ImageNet ILSVRC-2012 (Russakovsky et al., 2015).
For all methods we analyze test negative log-likelihood, which reflects both the accuracy and the quality of predictive uncertainty. Following Guo et al. (2017) we also consider a variant of reliability diagrams to evaluate the calibration of uncertainty estimates (see Figure 3) and to show the difference between a method’s confidence in its predictions and its accuracy. To produce this plot for a given method we split the test data into bins uniformly based on the confidence of a method (maximum predicted probability). We then evaluate the accuracy and mean confidence of the method on the images from each bin, and plot the difference between confidence and accuracy. For a well-calibrated model, this difference should be close to zero for each bin. We found that this procedure gives a more effective visualization of the actual confidence distribution of DNN predictions than the standard reliability diagrams used in Guo et al. (2017) and Niculescu-Mizil & Caruana (2005).
We provide tables containing the test accuracy, negative log likelihood and expected calibration error for all methods and datasets in Appendix D.
On CIFAR datasets we run experiments with VGG-16, PreResNet-164 and WideResNet-28x10 networks. In order to compare SWAG with existing alternatives we report the results for standard SGD and SWA (Izmailov et al., 2018) solutions (single models), MC-Dropout (Gal & Ghahramani, 2016), temperature scaling (Guo et al., 2017) applied to SWA and SGD solutions, and K-FAC Laplace (Ritter et al., 2018b) methods. For all the methods we use our implementations in PyTorch (see Appendix D.1). We train all networks for epochs, starting to collect models for SWA and SWAG approximations once per epoch after epoch . For SWAG, K-FAC Laplace, and Dropout we use 30 samples at test time.
On ImageNet we report our results for SWAG, SWAG-Diagonal, SWA and SGD. We run experiments with DenseNet-161 (Huang et al., 2017) and Resnet-152 (He et al., 2016). For each model we start from a pre-trained model available in the torchvision package, and run SGD with a constant learning rate for epochs. We collect models for the SWAG versions and SWA times per epoch. For SWAG we use samples from the posterior over network weights at test-time, and use randomly sampled of the training data to update batch-normalization statistics for each of the samples. For SGD with temperature scaling, we use the results reported in Guo et al. (2017).
We provide further details on the architectures and hyperparameter choices in Appendix D.1.
We visualize the negative log-likelihood for all methods and datasets in Figure 2. On all considered tasks SWAG and SWAG diagonal perform comparably or better than all the considered alternatives, SWAG being best overall. We note that the combination of SWA and temperature scaling presents a competitive baseline. However, unlike SWAG it requires using a validation set to tune the temperature; further, temperature scaling is not effective when the test data distribution differs from train. We consider this setting in Sections 5.2 and 5.3.
Next, we analyze the calibration of uncertainty estimates provided by different methods. In Figure 3 we present reliability plots for WideResNet on CIFAR-100, DenseNet-161 and ResNet-152 on ImageNet. The reliability diagrams for all other datasets and architectures are presented in the Appendix D.3. As we can see, SWAG and SWAG-Diagonal both achieve good calibration across the board. The low-rank plus diagonal version of SWAG is generally better calibrated than SWAG-Diagonal. We also present the expected calibration error for each of the methods, architectures and datasets in Table A.2.
Finally, in Table A.4 we present the predictive accuracy for all of the methods. SWAG verions generally perform comparably to SWA in terms of predictive accuracy and outperform the other methods that do not use SWA.
Method | JS-Distance |
---|---|
SWAG | 3.31 |
SWAG-Diag | 2.27 |
MC Dropout | 3.04 |
SWA | 1.68 |
SGD (Baseline) | 3.14 |
SGD + Temp. Scaling | 2.98 |
We evaluate the uncertainties provided by SWAG, SWAG-Diagonal and baselines in the transfer-learning setting. We use the models trained on CIFAR-10 and evaluate them on STL-10 (Coates et al., 2011). STL-10 has a similar set of classes as CIFAR-10, but the image distribution is different, so adapting the model from CIFAR-10 to STL-10 is a commonly used benchmark in transfer learning.
The test negative log-likelihood for all methods is given in Figure 2, and Figure 3 contains the reliability diagram for WideResNet-28x10. As we can see, in transfer learning setting SWAG is significantly outperforming the existing alternatives both in terms of likelihood and calibration. In particular SWA with temperature scaling does not match the performance of SWAG, since the data distribution used to scale the temperature is different from the test distribution. See Appendix D.2 for detailed results for all architectures.
Next, we evaluate the SWAG variants along with the baselines on out-of-sample data detection. To do so we train a WideResNet as described in section 5.1 on the data from five classes of the CIFAR-10 dataset, and then analyze their predictions on the full test set. We expect the outputted class probabilities on objects that belong to classes that were not present in the training data to have high-entropy reflecting the model’s high uncertainty in its predictions, and considerably lower entropy on the images that are similar to those on which the network was trained.
To make this comparison quantitative, we computed the symmetrized KL divergence between the binned in and out of sample distributions in Table 1, finding that SWAG and Dropout perform best on this measure. We plot the histograms of predictive entropies on the in-domain (classes that were trained on) and out-of-domain (classes that were not trained on) in Figure A.9 for a qualitative comparison.
In this paper we developed SWA-Gaussian (SWAG) for approximate Bayesian inference in deep learning. There has been a great desire to apply Bayesian methods in deep learning due to their theoretical properties and past success with small neural networks. We view SWAG as a step towards practical, scalable, and accurate Bayesian deep learning for large modern neural networks.
A key geometric observation in this paper is that the posterior distribution over neural network parameters is close to Gaussian in the subspace spanned by the trajectory of SGD. Further, this Gaussian distribution is remarkably well-aligned with the principal components (eigenvectors of sample covariance matrix) of the set of SGD iterates. The subspace spanned by SGD iterates is of interest for several reasons. First, our work shows that Bayesian model averaging within this subspace can improve predictions over SGD or SWA solutions. Second, Gur-Ari et al. (2019) argue that the SGD trajectory lies in the subspace spanned by the eigenvectors of the Hessian corresponding to the few top eigenvalues. This result suggests that we would expect the subspace containing SGD trajectory to correspond to directions of rapid change in the predictions of the model.
WM, PI, and AGW were supported by an Amazon Research Award, Facebook Research, and NSF IIS-1563887. WM was additionally supported by an NSF Graduate Research Fellowship under Grant No. DGE-1650441. We would like to thank Jacob Gardner for helpful discussions.
Proceedings of the Fourteenth International Conference on Artificial Intelligence and Statistics
, pp. 215–223, June 2011. URL http://proceedings.mlr.press/v15/coates11a.html.Bayesian Interpolation.
Neural Computation, 1992a. URL https://www.mitpressjournals.org/doi/pdf/10.1162/neco.1992.4.3.415.A Practical Bayesian Framework for Backpropagation Networks.
Neural Computation, 4(3):448–472, May 1992b. ISSN 0899-7667, 1530-888X. doi: 10.1162/neco.1992.4.3.448. URL http://www.mitpressjournals.org/doi/10.1162/neco.1992.4.3.448.Predicting good probabilities with supervised learning.
In International Conference on Machine Learning, pp. 625–632, Bonn, Germany, 2005. ACM Press. ISBN 978-1-59593-180-1. doi: 10.1145/1102351.1102430. URL http://portal.acm.org/citation.cfm?doid=1102351.1102430.Improving Stability in Deep Reinforcement Learning with Weight Averaging.
In Uncertainty in Artificial Intelligence Workshop on Uncertainty in Deep Learning, pp. 5, 2018.To estimate from the gradient noise we need to divide the estimated variance by the batch size (as ), for a correct version of Equation 5. From Assumption 1 and Equation 6 of Mandt et al. (2017), we see that
where is the batch size. Thus, collecting the variance of (the variance of the stochastic gradients) will give estimates that are upscaled by a factor of :
To include momentum, we can repeat the analysis in Sections 4.1 and 4.3 Mandt et al. (2017) finding that this also involves scaling the optimal learning rate but by a factor of the momentum term. This gives the final optimal learning rate equation as
(6) |
In Figure 3(b), we computed for VGG-16 and PreResNet-164 on CIFAR-100 beginning from the start of training (referred to as from scratch), as well as the start of the SWAG procedure (referred to in the legend as SWA). We see that is never quite constant when trained from scratch, while for a period of constant learning rate near the end of training, referred to as the stationary phase, is essentially constant throughout. This discrepancy is likely due to large gradients at the very beginning of training, indicating that the stationary distribution has not been reached yet.
Next, in Figure 3(a), we used the computed estimate for all four models and Equation 6 to compute the optimal learning rate under the assumptions of Mandt et al. (2017), finding that these learning rates are not constant for the estimates beginning at the start of training and that they are always way too large (3,000 at the minimum compared to a standard learning rate of 0.1).
In Figure 5 we present plots analogous to those in Section 4 for PreResNet-110 and VGG-16 on CIFAR-10 and CIFAR-100. For all dataset-architecture pairs we see that SWAG is able to capture the geometry of the posterior in the subspace spanned by SGD trajectory.
In this section, we discuss the hyper-parameters in SWAG, as well as some current theoretical limitations.
We now evaluate the effect of the covariance matrix rank on the SWAG approximation. To do so, we trained a PreResNet56 on CIFAR-100 with SWAG beginning from epoch 161, and evaluated 30 sample Bayesian model averages obtained at different epochs; the accuracy plot from this experiment is shown in Figure 6 (a). The rank of each model after epoch 161 is simply and we can see that the 30 samples from even a low rank approximation reach the same predictive accuracy as the SWA model. Interestingly, both SWAG and SWA outperform ensembles of a SGD run and ensembles of the SGD models in the SWA run.
In most situations where SWAG will be used, no closed form expression for the integral will exist. Thus, Monte Carlo approximations will be used; Monte Carlo integration converges at a rate of where is the number of samples used, but practically good results may be found with very few samples (e.g. Chapter 29 of MacKay (2003)).
To test how many samples are needed for good predictive accuracy in a Bayesian model averaging task, we used a rank 20 approximation for SWAG and then tested the NLL on the test set as a function of the number of samples for WideResNet28x10 (Zagoruyko & Komodakis, 2016) on CIFAR-100.
The results from this experiment are shown in Figure 6 (b, c), where it is possible to see that about 3 samples will match the SWA result for NLL, with about 30 samples necessary for stable accuracy (about the same as SWA for this network). In most of our experiments, we used 30 samples for consistency. In practice, we suggest tuning this number by looking at a validation set as well as the computational resources available and comparing to the free SWA predictions that come with SWAG.
First, we note that the covariance, estimated using SWAG, is a function of the learning rate (and momentum) for SGD. While the theoretical work of Mandt et al. (2017) suggests that it is possible to optimally set the learning rate, our experiments in Section 4.2 show that currently the assumptions of the theory do not match the empirical reality in deep learning. In the linear setting as in Mandt et al. (2017), the learning rate controls the scale of the asymptotic covariance matrix. If the optimal learning rate (Equation 5) is used in this setting, the covariance matches the true posterior. To attempt to disassociate the learning rate from the covariance in practice, we rescale the covariance matrix when sampling by a constant factor for a WideResNet on CIFAR-100 shown in Figure 6 (d).
Over several replications, we found that a scale of 0.5 worked best, which is expected because the low rank plus diagonal covariance incorporates the variance twice (once for the diagonal component and once from the low rank component).
One possible slowdown of SWAG at inference time is in the usage of updated batch norm parameters. Following Izmailov et al. (2018), we found that in order for the averaging and sampling to work well, it was necessary to update the batch norm parameters of networks after sampling a new model. This is shown in Figure 7 for a WideResNet on CIFAR-100 for two independently trained models.
From our experimental findings, we see that given an equal amount of training time, SWAG typically outperforms other methods for uncertainty calibration. SWAG additionally does not require a validation set like temperature scaling and Platt scaling (e.g. Guo et al. (2017); Kuleshov et al. (2018)). SWAG also appears to have a distinct advantage over temperature scaling, and other popular alternatives, when the target data are from a different distribution than the training data, as shown by our transfer learning experiments.
Deep ensembles (Lakshminarayanan et al., 2017) require several times longer training for equal calibration, but often perform somewhat better due to incorporating several independent training runs. Thus SWAG will be particularly valuable when training time is limited, but inference time may not be. One possible application is thus in medical applications when image sizes (for semantic segmentation) are large, but predictions can be parallelized and may not have to be instantaneous.
In this section we describe all of the architectures and hyper-parameters we use in Sections 5.1, 5.3.
On ImageNet we use architecture implementations and pre-trained weights from https://github.com/pytorch/vision/tree/master/torchvision. For the experiments on CIFAR datasets we adapted the following implementations:
VGG-: https://github.com/pytorch/vision/blob/master/torchvision/models/vgg.py
Preactivation-ResNet-: https://github.com/bearpaw/pytorch-classification/blob/master/models/cifar/preresnet.py
WideResNet28x10: https://github.com/meliketoy/wide-resnet.pytorch/blob/master/networks/wide_resnet.py
For all datasets and architectures we use the same piecewise constant learning rate schedule and weight decay as in Izmailov et al. (2018), except we train Pre-ResNet for epochs and start averaging after epoch in SWAG and SWA. For all of the methods we are using our own implementations in PyTorch. We describe the hyper-parameters for all experiments for each model:
We use the same hyper-parameters as Izmailov et al. (2018) on CIFAR datasets. On ImageNet we used a constant learning rate of instead of the cyclical schedule, and averaged models per epoch. We adapt the code from https://github.com/timgaripov/swa for our implementation of SWA.
In all experiments we use rank and use weight samples for Bayesian model averaging. We re-use all the other hyper-parameters from SWA.
For our implementation we adapt the code for KFAC Fisher approximation from https://github.com/Thrandis/EKFAC-pytorch and implement our own code for sampling. Following (Ritter et al., 2018b) we tune the scale of the approximation on validation set for every model and dataset.
In order to implement MC-dropout we add dropout layers before each weight layer and sample different dropout masks for Bayesian model averaging at inference time. To choose the learning rate, we ran the models with drop out rates in the set and chose the one that performed best on validation data. For both VGG-16 and WideResNet28x10 we found that dropout rate of worked best and used it in all experiments. On PreResNet-164 we couldn’t achieve reasonable performance with any of the three dropout rates, which has been reported from the work of He et al. (2016). We report the results for MC-Dropout in combination with both SWA (SWA-Drop) and SGD (SGD-Drop) training.
For SWA and SGD solutions we picked the optimal temperature by minimizing negative log-likelihood on validation data, adapting the code from https://github.com/gpleiss/temperature_scaling.
On CIFAR datasets for tuning hyper-parameters we used the last training data points as a validation set. On ImageNet we used of test data points for validation. On the transfer task for CIFAR10 to STL10, we report accuracy on all 10 STL10 classes even though frogs are not a part of the STL10 test set (and monkeys are not a part of the CIFAR10 training set).
We provide test accuracies and negative log-likelihoods (NLL) for all methods and datasets in Tables 3 and 4 respectively. We observe that SWAG is competitive with SWA, SWA with temperature scaling and SWA-Dropout in terms of test accuracy, and typically outperforms all the baselines in terms of NLL. SWAG-Diagonal is generally inferior to SWAG for log-likelihood, but outperforms SWA.
In Table 2 we additionally report expected calibration error (ECE, Naeini et al., 2015), a metric of calibration of the predictive uncertainties. To compute ECE for a given model we split the test points into bins based on the confidence of the model, and we compute the absolute value of the difference of the average confidence and accuracy within each bin, and average the obtained values over all bins. Please refer to (Naeini et al., 2015; Guo et al., 2017) for more details. We observe that SWAG is competitive with temperature scaling for ECE. Again, SWAG-Diagonal achieves better calibration than SWA, but using the low-rank plus diagonal covariance approximation in SWAG leads to substantially improved performance.
We provide the additional reliability diagrams for all methods and datasets in Figure 8. SWAG consistently improves calibration over SWA, and performs on par or better than temperature scaling. In transfer learning temperature scaling fails to achieve good calibration, while SWAG still provides a significant improvement over SWA.
Table 1 shows the computed symmetrized, discretized KL distance between in and out of sample distributions for the CIFAR5 out of sample image detection class. We used the same bins as in Figure 9 to discretize the entropy distributions, then smoothed these bins by a factor of 1e-7 before calculating using the scipy.stats.entropy function. We can see even qualitatively that the distributions are more distinct for SWAG and SWAG-Diagonal than for the other methods, particularly temperature scaling.
Dataset | Model | SGD | SWA | SWAG-Diag | SWAG | KFAC-Laplace | SWA-Dropout | SWA-Temp |
---|---|---|---|---|---|---|---|---|
CIFAR-10 | VGG-16 | |||||||
CIFAR-10 | PreResNet-164 | |||||||
CIFAR-10 | WideResNet28x10 | |||||||
CIFAR-100 | VGG-16 | |||||||
CIFAR-100 | PreResNet-164 | |||||||
CIFAR-100 | WideResNet28x10 | |||||||
ImageNet | DenseNet-161 | |||||||
ImageNet | ResNet-152 | |||||||
CIFAR10 STL10 | VGG-16 | |||||||
CIFAR10 STL10 | PreResNet-164 | |||||||
CIFAR10 STL10 | WideResNet28x10 |
Dataset | Model | SGD | SWA | SWAG-Diag | SWAG | KFAC-Laplace | SWA-Dropout | SWA-Temp |
---|---|---|---|---|---|---|---|---|
CIFAR-10 | VGG-16 | |||||||
CIFAR-10 | PreResNet-164 | |||||||
CIFAR-10 | WideResNet28x10 | |||||||
CIFAR-100 | VGG-16 | |||||||
CIFAR-100 | PreResNet-164 | |||||||
CIFAR-100 | WideResNet28x10 | |||||||
ImageNet | DenseNet-161 | |||||||
ImageNet | ResNet-152 | |||||||
CIFAR10 STL10 | VGG-16 | |||||||
CIFAR10 STL10 | PreResNet-164 | |||||||
CIFAR10 STL10 | WideResNet28x10 |
Dataset | Model | SGD | SWA | SWAG-Diag | SWAG | KFAC-Laplace | SWA-Dropout | SWA-Temp |
---|---|---|---|---|---|---|---|---|
CIFAR-10 | VGG-16 | |||||||
CIFAR-10 | PreResNet-164 | |||||||
CIFAR-10 | WideResNet28x10 | |||||||
CIFAR-100 | VGG-16 | |||||||
CIFAR-100 | PreResNet-164 | |||||||
CIFAR-100 | WideResNet28x10 | |||||||
ImageNet | DenseNet-161 | |||||||
ImageNet | ResNet-152 | |||||||
CIFAR10 STL10 | VGG-16 | |||||||
CIFAR10 STL10 | PreResNet-164 | |||||||
CIFAR10 STL10 | WideResNet28x10 |