Path: blob/master/site/en-snapshot/tutorials/understanding/sngp.ipynb
25118 views
Copyright 2021 The TensorFlow Authors.
Uncertainty-aware Deep Learning with SNGP
In AI applications that are safety-critical, such as medical decision making and autonomous driving, or where the data is inherently noisy (for example, natural language understanding), it is important for a deep classifier to reliably quantify its uncertainty. The deep classifier should be able to be aware of its own limitations and when it should hand control over to the human experts. This tutorial shows how to improve a deep classifier's ability in quantifying uncertainty using a technique called Spectral-normalized Neural Gaussian Process (SNGP{.external}).
The core idea of SNGP is to improve a deep classifier's distance awareness by applying simple modifications to the network. A model's distance awareness is a measure of how its predictive probability reflects the distance between the test example and the training data. This is a desirable property that is common for gold-standard probabilistic models (for example, the Gaussian process{.external} with RBF kernels) but is lacking in models with deep neural networks. SNGP provides a simple way to inject this Gaussian-process behavior into a deep classifier while maintaining its predictive accuracy.
This tutorial implements a deep residual network (ResNet)-based SNGP model on scikit-learn’s two moons{.external} dataset, and compares its uncertainty surface with that of two other popular uncertainty approaches: Monte Carlo dropout{.external} and Deep ensemble{.external}.
This tutorial illustrates the SNGP model on a toy 2D dataset. For an example of applying SNGP to a real-world natural language understanding task using a BERT-base, check out the SNGP-BERT tutorial. For high-quality implementations of an SNGP model (and many other uncertainty methods) on a wide variety of benchmark datasets (such as CIFAR-100, ImageNet, Jigsaw toxicity detection, etc), refer to the Uncertainty Baselines{.external} benchmark.
About SNGP
SNGP is a simple approach to improve a deep classifier's uncertainty quality while maintaining a similar level of accuracy and latency. Given a deep residual network, SNGP makes two simple changes to the model:
It applies spectral normalization to the hidden residual layers.
It replaces the Dense output layer with a Gaussian process layer.
Compared to other uncertainty approaches (such as Monte Carlo dropout or Deep ensemble), SNGP has several advantages:
It works for a wide range of state-of-the-art residual-based architectures (for example, (Wide) ResNet, DenseNet, or BERT).
It is a single-model method—it does not rely on ensemble averaging). Therefore, SNGP has a similar level of latency as a single deterministic network, and can be scaled easily to large datasets like ImageNet{.external} and Jigsaw Toxic Comments classification{.external}.
It has strong out-of-domain detection performance due to the distance-awareness property.
The downsides of this method are:
The predictive uncertainty of SNGP is computed using the Laplace approximation{.external}. Therefore, theoretically, the posterior uncertainty of SNGP is different from that of an exact Gaussian process.
SNGP training needs a covariance reset step at the beginning of a new epoch. This can add a tiny amount of extra complexity to a training pipeline. This tutorial shows a simple way to implement this using Keras callbacks.
Setup
Define visualization macros
The two moon dataset
Create the training and evaluation datasets from the scikit-learn two moon dataset{.external}.
Evaluate the model's predictive behavior over the entire 2D input space.
To evaluate model uncertainty, add an out-of-domain (OOD) dataset that belongs to a third class. The model never observes these OOD examples during training.
Here, the blue and orange represent the positive and negative classes, and the red represents the OOD data. A model that quantifies the uncertainty well is expected to be confident when close to training data (i.e., close to 0 or 1), and be uncertain when far away from the training data regions (i.e., close to 0.5).
The deterministic model
Define model
Start from the (baseline) deterministic model: a multi-layer residual network (ResNet) with dropout regularization.
This tutorial uses a six-layer ResNet with 128 hidden units.
Train model
Configure the training parameters to use SparseCategoricalCrossentropy
as the loss function and the Adam optimizer.
Train the model for 100 epochs with batch size 128.
Visualize uncertainty
Now visualize the predictions of the deterministic model. First plot the class probability:
In this plot, the yellow and purple are the predictive probabilities for the two classes. The deterministic model did a good job in classifying the two known classes—blue and orange—with a nonlinear decision boundary. However, it is not distance-aware, and classified the never-observed red out-of-domain (OOD) examples confidently as the orange class.
Visualize the model uncertainty by computing the predictive variance:
In this plot, the yellow indicates high uncertainty, and the purple indicates low uncertainty. A deterministic ResNet's uncertainty depends only on the test examples' distance from the decision boundary. This leads the model to be over-confident when out of the training domain. The next section shows how SNGP behaves differently on this dataset.
The SNGP model
Define SNGP model
Let's now implement the SNGP model. Both the SNGP components, SpectralNormalization
and RandomFeatureGaussianProcess
, are available at the tensorflow_model's built-in layers.
Let's inspect these two components in more detail. (You can also jump to the full SNGP model section to learn how SNGP is implemented.)
SpectralNormalization
wrapper
SpectralNormalization
{.external} is a Keras layer wrapper. It can be applied to an existing Dense layer like this:
Spectral normalization regularizes the hidden weight by gradually guiding its spectral norm (that is, the largest eigenvalue of ) toward the target value norm_multiplier
).
Note: Usually it is preferable to set norm_multiplier
to a value smaller than 1. However in practice, it can be also relaxed to a larger value to ensure the deep network has enough expressive power.
The Gaussian Process (GP) layer
RandomFeatureGaussianProcess
{.external} implements a random-feature based approximation{.external} to a Gaussian process model that is end-to-end trainable with a deep neural network. Under the hood, the Gaussian process layer implements a two-layer network:
Here, is the input, and and are frozen weights initialized randomly from Gaussian and Uniform distributions, respectively. (Therefore, are called "random features".) is the learnable kernel weight similar to that of a Dense layer.
The main parameters of the GP layers are:
units
: The dimension of the output logits.num_inducing
: The dimension of the hidden weight . Default to 1024.normalize_input
: Whether to apply layer normalization to the input .scale_random_features
: Whether to apply the scale to the hidden output.
Note: For a deep neural network that is sensitive to the learning rate (for example, ResNet-50 and ResNet-110), it is generally recommended to set normalize_input=True
to stabilize training, and set scale_random_features=False
to avoid the learning rate from being modified in unexpected ways when passing through the GP layer.
gp_cov_momentum
controls how the model covariance is computed. If set to a positive value (for example,0.999
), the covariance matrix is computed using the momentum-based moving average update (similar to batch normalization). If set to-1
, the covariance matrix is updated without momentum.
Note: The momentum-based update method can be sensitive to batch size. Therefore it is generally recommended to set gp_cov_momentum=-1
to compute the covariance exactly. For this to work properly, the covariance matrix estimator needs to be reset at the beginning of a new epoch in order to avoid counting the same data twice. For RandomFeatureGaussianProcess
, this can be done by calling its reset_covariance_matrix()
. The next section shows an easy implementation of this using Keras' built-in API.
Given a batch input with shape (batch_size, input_dim)
, the GP layer returns a logits
tensor (shape (batch_size, num_classes)
) for prediction, and also covmat
tensor (shape (batch_size, batch_size)
) which is the posterior covariance matrix of the batch logits.
Note: Notice that under this implementation of the SNGP model, the predictive logits for all classes share the same covariance matrix , which describes the distance between from the training data.
Theoretically, it is possible to extend the algorithm to compute different variance values for different classes (as introduced in the original SNGP paper{.external}). However, this is difficult to scale to problems with large output spaces (such as classification with ImageNet or language modeling).
Given the base class DeepResNet
, the SNGP model can be implemented easily by modifying the residual network's hidden and output layers. For compatibility with Keras model.fit()
API, also modify the model's call()
method so it only outputs logits
during training.
Use the same architecture as the deterministic model.
Add this callback to the DeepResNetSNGP
model class.
Train model
Use tf.keras.model.fit
to train the model.
Visualize uncertainty
First compute the predictive logits and variances.
Now compute the posterior predictive probability. The classic method for computing the predictive probability of a probabilistic model is to use Monte Carlo sampling, i.e.,
where is the sample size, and are random samples from the SNGP posterior (sngp_logits
,sngp_covmat
). However, this approach can be slow for latency-sensitive applications such as autonomous driving or real-time bidding. Instead, you can approximate using the mean-field method{.external}:
where is the SNGP variance, and is often chosen as or .
Note: Instead of fixing to a fixed value, you can also treat it as a hyperparameter, and tune it to optimize the model's calibration performance. This is known as temperature scaling{.external} in the deep learning uncertainty literature.
This mean-field method is implemented as a built-in function layers.gaussian_process.mean_field_logits
:
SNGP Summary
You can now put everything together. The entire procedure—training, evaluation and uncertainty computation—can be done in just five lines:
Visualize the class probability (left) and the predictive uncertainty (right) of the SNGP model.
Remember that in the class probability plot (left), the yellow and purple are class probabilities. When close to the training data domain, SNGP correctly classifies the examples with high confidence (i.e., assigning near 0 or 1 probability). When far away from the training data, SNGP gradually becomes less confident, and its predictive probability becomes close to 0.5 while the (normalized) model uncertainty rises to 1.
Compare this to the uncertainty surface of the deterministic model:
As mentioned earlier, a deterministic model is not distance-aware. Its uncertainty is defined by the distance of the test example from the decision boundary. This leads the model to produce overconfident predictions for the out-of-domain examples (red).
Comparison with other uncertainty approaches
This section compares the uncertainty of SNGP with Monte Carlo dropout{.external} and Deep ensemble{.external}.
Both of these methods are based on Monte Carlo averaging of multiple forward passes of deterministic models. First, set the ensemble size .
Monte Carlo dropout
Given a trained neural network with Dropout layers, Monte Carlo dropout computes the mean predictive probability
by averaging over multiple Dropout-enabled forward passes .
Deep ensemble
Deep ensemble is a state-of-the-art (but expensive) method for deep learning uncertainty. To train a Deep ensemble, first train ensemble members.
Collect logits and compute the mean predictive probability .
Both the Monte Carlo Dropout and Deep ensemble methods improve the model's uncertainty ability by making the decision boundary less certain. However, they both inherit the deterministic deep network's limitation in lacking distance awareness.
Summary
In this tutorial, you have:
Implemented the SNGP model on a deep classifier to improve its distance awareness.
Trained the SNGP model end-to-end using Keras
Model.fit
API.Visualized the uncertainty behavior of SNGP.
Compared the uncertainty behavior between SNGP, Monte Carlo dropout and deep ensemble models.
Resources and further reading
Check out the SNGP-BERT tutorial for an example of applying SNGP on a BERT model for uncertainty-aware natural language understanding.
Go to the Uncertainty Baselines GitHub repo{.external} for the implementation of SNGP model (and many other uncertainty methods) on a wide variety of benchmark datasets (for example, CIFAR, ImageNet, Jigsaw toxicity detection, etc).
For a deeper understanding of the SNGP method, check out the paper titled Simple and Principled Uncertainty Estimation with Deterministic Deep Learning via Distance Awareness{.external}.