This page was generated from doc/source/od/methods/vaegmm.ipynb.

# Variational Auto-Encoding Gaussian Mixture Model¶

## Overview¶

The Variational Auto-Encoding Gaussian Mixture Model (VAEGMM) Outlier Detector follows the Deep Autoencoding Gaussian Mixture Model for Unsupervised Anomaly Detection paper but with a VAE instead of a regular Auto-Encoder. The encoder compresses the data while the reconstructed instances generated by the decoder are used to create additional features based on the reconstruction error between the input and the
reconstructions. These features are combined with encodings and fed into a Gaussian Mixture Model (GMM). The VAEGMM outlier detector is first trained on a batch of unlabeled, but normal (*inlier*) data. Unsupervised or semi-supervised training is desirable since labeled data is often scarce. The sample energy of the GMM can then be used to determine whether an instance is an outlier (high sample energy) or not (low sample
energy). The algorithm is suitable for tabular and image data.

## Usage¶

### Initialize¶

Parameters:

`threshold`

: threshold value for the sample energy above which the instance is flagged as an outlier.`latent_dim`

: latent dimension of the VAE.`n_gmm`

: number of components in the GMM.`encoder_net`

:`tf.keras.Sequential`

instance containing the encoder network. Example:

```
encoder_net = tf.keras.Sequential(
[
InputLayer(input_shape=(n_features,)),
Dense(60, activation=tf.nn.tanh),
Dense(30, activation=tf.nn.tanh),
Dense(10, activation=tf.nn.tanh),
Dense(latent_dim, activation=None)
])
```

`decoder_net`

:`tf.keras.Sequential`

instance containing the decoder network. Example:

```
decoder_net = tf.keras.Sequential(
[
InputLayer(input_shape=(latent_dim,)),
Dense(10, activation=tf.nn.tanh),
Dense(30, activation=tf.nn.tanh),
Dense(60, activation=tf.nn.tanh),
Dense(n_features, activation=None)
])
```

`gmm_density_net`

: layers for the GMM network wrapped in a`tf.keras.Sequential`

class. Example:

```
gmm_density_net = tf.keras.Sequential(
[
InputLayer(input_shape=(latent_dim + 2,)),
Dense(10, activation=tf.nn.tanh),
Dense(n_gmm, activation=tf.nn.softmax)
])
```

`vaegmm`

: instead of using a separate encoder, decoder and GMM density net, the VAEGMM can also be passed as a`tf.keras.Model`

.`samples`

: number of samples drawn during detection for each instance to detect.`beta`

: weight on the KL-divergence loss term following the \(\beta\)-VAE framework. Default equals 1.`recon_features`

: function to extract features from the reconstructed instance by the decoder. Defaults to a combination of the mean squared reconstruction error and the cosine similarity between the original and reconstructed instances by the VAE.`data_type`

: can specify data type added to metadata. E.g.*‘tabular’*or*‘image’*.

Initialized outlier detector example:

```
from alibi_detect.od import OutlierVAEGMM
od = OutlierVAEGMM(
threshold=7.5,
encoder_net=encoder_net,
decoder_net=decoder_net,
gmm_density_net=gmm_density_net,
latent_dim=4,
n_gmm=2,
samples=10
)
```

### Fit¶

We then need to train the outlier detector. The following parameters can be specified:

`X`

: training batch as a numpy array of preferably normal data.`loss_fn`

: loss function used for training. Defaults to the custom VAEGMM loss which is a combination of the elbo loss, sample energy of the GMM and a loss term penalizing small values on the diagonals of the covariance matrices in the GMM to avoid trivial solutions. It is important to balance the loss weights below so no single loss term dominates during the optimization.`w_recon`

: weight on elbo loss term. Defaults to 1e-7.`w_energy`

: weight on sample energy loss term. Defaults to 0.1.`w_cov_diag`

: weight on covariance diagonals. Defaults to 0.005.`optimizer`

: optimizer used for training. Defaults to Adam with learning rate 1e-4.`cov_elbo`

: dictionary with covariance matrix options in case the elbo loss function is used. Either use the full covariance matrix inferred from X (*dict(cov_full=None)*), only the variance (*dict(cov_diag=None)*) or a float representing the same standard deviation for each feature (e.g.*dict(sim=.05)*) which is the default.`epochs`

: number of training epochs.`batch_size`

: batch size used during training.`verbose`

: boolean whether to print training progress.`log_metric`

: additional metrics whose progress will be displayed if verbose equals True.

```
od.fit(
X_train,
epochs=10,
batch_size=1024
)
```

It is often hard to find a good threshold value. If we have a batch of normal and outlier data and we know approximately the percentage of normal data in the batch, we can infer a suitable threshold:

```
od.infer_threshold(
X,
threshold_perc=95
)
```

### Detect¶

We detect outliers by simply calling `predict`

on a batch of instances `X`

to compute the instance level sample energies. We can also return the instance level outlier score by setting `return_instance_score`

to True.

The prediction takes the form of a dictionary with `meta`

and `data`

keys. `meta`

contains the detector’s metadata while `data`

is also a dictionary which contains the actual predictions stored in the following keys:

`is_outlier`

: boolean whether instances are above the threshold and therefore outlier instances. The array is of shape*(batch size,)*.`instance_score`

: contains instance level scores if`return_instance_score`

equals True.

```
preds = od.predict(
X,
return_instance_score=True
)
```