fusionlab.nn.anomaly_detection.LSTMAutoencoderAnomaly¶
- class fusionlab.nn.anomaly_detection.LSTMAutoencoderAnomaly[source]¶
Bases:
Model,NNLearner- LSTM Autoencoder for time series reconstruction-based anomaly
detection.
This layer implements a configurable LSTM autoencoder architecture. It encodes an input sequence into a lower-dimensional latent representation and then decodes this representation back into a sequence, attempting to reconstruct the original input. Training typically involves minimizing the reconstruction error on normal data.
The core idea is that anomalous sequences, deviating from patterns learned on normal data, will result in higher reconstruction errors, which can serve as anomaly scores. This layer offers flexibility in the number of encoder/decoder layers, bidirectionality, bottleneck configuration, output feature dimension specification, and the length of the reconstructed sequence.
- Parameters:
latent_dim (
int) – Dimensionality of the latent space (bottleneck). This controls the degree of information compression. If use_bottleneck_dense is True, this defines the output size of the bottleneck Dense layer applied to the final encoder hidden state. If False, this parameter might not be directly used (effective latent dim depends on lstm_units and use_bidirectional_encoder).lstm_units (
int) – Number of hidden units in each LSTM layer for both the encoder and decoder. Determines the capacity of the LSTMs.n_features (
int, optional, defaultNone) –Allows pre-specifying the number of output features (last dimension) for the reconstructed sequence. * If an integer is provided, the final TimeDistributed(Dense)
layer is created during initialization with this many units. An error will be raised during the build step if the actual input feature dimension doesn’t match this value.
If
None(default), the number of output features is inferred from the input data’s feature dimension during the build step.
n_repeats (
int, optional, defaultNone) –Specifies a fixed number of time steps for the output sequence generated by the decoder. * If an integer is provided, the latent vector from the encoder
is repeated n_repeats times before being fed into the decoder LSTM stack. The output reconstruction will have this many time steps, regardless of the input sequence length.
If
None(default), the latent vector is repeated a number of times equal to the number of time steps in the input sequence, aiming to reconstruct the input fully.
num_encoder_layers (
int, default1) – Number of LSTM layers stacked in the encoder. Must be >= 1.num_decoder_layers (
int, default1) – Number of LSTM layers stacked in the decoder. Must be >= 1.activation (
str, default'tanh') – Activation function applied to the final TimeDistributed Dense output layer of the decoder, reconstructing the features. Examples: ‘tanh’, ‘sigmoid’, ‘linear’. Choose based on the expected range or normalization of the input data.intermediate_activation (
str, default'relu') – Activation function used in the optional bottleneck Dense layers (if use_bottleneck_dense=True).dropout_rate (
float, default0.0) – Dropout rate applied to the non-recurrent connections (inputs and outputs) of the LSTM layers. Value between 0 and 1.recurrent_dropout_rate (
float, default0.0) – Dropout rate applied to the recurrent connections within the LSTM layers. Value between 0 and 1. Note: Using recurrent dropout may require disabling GPU acceleration (CuDNN) for LSTMs.use_bidirectional_encoder (
bool, defaultFalse) – If True, wraps the encoder LSTM layers with a Bidirectional wrapper, processing the input sequence in both forward and backward directions. The final hidden states are typically concatenated.use_bottleneck_dense (
bool, defaultFalse) – If True, adds Dense layers after the final encoder LSTM layer to explicitly project the final hidden state (state_h) and cell state (state_c) to the specified latent_dim. If False, the final encoder states are used directly.**kwargs – Additional keyword arguments passed to the parent Keras Layer.
Notes
This layer expects input data with the shape (Batch, TimeSteps, Features). The output shape will be (Batch, OutputTimeSteps, OutputFeatures), where OutputTimeSteps is determined by n_repeats (or input TimeSteps if n_repeats is None) and OutputFeatures is determined by n_features (or input Features if n_features is None).
Use Case and Importance
This component is primarily used for unsupervised anomaly detection in sequential data. By training the autoencoder primarily on normal data, it learns the underlying patterns and structure inherent in that normal behavior. When presented with new data, sequences conforming to these learned patterns will be reconstructed accurately (low error), while sequences containing anomalies or novel patterns will result in poor reconstructions (high error). This reconstruction error serves as a valuable, data-driven anomaly score, particularly useful when labeled anomaly data is scarce or unavailable. The added flexibility via n_features and n_repeats allows for potential sequence-to-sequence tasks beyond pure reconstruction or handling cases where output dimensions differ from input.
Mathematical Formulation
The enhanced LSTM autoencoder involves:
Encoder: A stack of num_encoder_layers LSTMs (optionally bidirectional) processes the input sequence \(\mathbf{X} \in \mathbb{R}^{T \times F}\). The final layer outputs the last hidden state \(h_T\) and cell state \(c_T\).
\[[h_T, c_T] = \text{Encoder}_{LSTM\_Stack}(\mathbf{X})\]Bottleneck (Optional): If use_bottleneck_dense=True, the final states are projected to latent_dim: \(h'_T = \text{Dense}_{h}(h_T)\), \(c'_T = \text{Dense}_{c}(c_T)\). The latent vector used for decoding is \(\mathbf{z} = h'_T\). The decoder initial state is \([h'_T, c'_T]\). If False, \(\mathbf{z} = h_T\) and the initial state is \([h_T, c_T]\).
Decoder Input Repetition: The latent vector \(\mathbf{z}\) is repeated $T’$ times using
RepeatVector, where $T’ = text{n_repeats}$ if specified, otherwise $T’ = T$ (input time steps).\[\begin{split}\mathbf{Z}_{repeated} = \text{Repeat}(\mathbf{z})\\ \in \mathbb{R}^{T' \times \text{dim}(\mathbf{z})}\end{split}\]Decoder: A stack of num_decoder_layers LSTMs processes \(\mathbf{Z}_{repeated}\), initialized with the final (potentially bottlenecked) state from the encoder.
\[\begin{split}\mathbf{H}_{dec} = \text{Decoder}_{LSTM\_Stack}\\ (\mathbf{Z}_{repeated}, \text{initial_state}) \in\\ \mathbb{R}^{T' \times \text{lstm\_units}}\end{split}\]Reconstruction: A
TimeDistributedDense layer maps the decoder’s output sequence \(\mathbf{H}_{dec}\) to the target feature dimension $F’$ (where $F’ = text{n_features}$ if specified, otherwise $F’=F$).\[\begin{split}\mathbf{\hat{X}} = \text{TimeDistributed}(\text{Dense}(\mathbf{H}_{dec}))\\ \in \mathbb{R}^{T' \times F'}\end{split}\]
The anomaly score is typically the reconstruction error, e.g., \(Error = ||\mathbf{X}_{[:T'',:F'']} - \mathbf{\hat{X}}_{[:T'',:F']}||^2\), where comparison might be limited to overlapping dimensions if $T’ neq T$ or $F’ neq F$. The compute_reconstruction_error method handles comparison over potentially differing time steps.
- call(inputs, training=False)[source]¶
Performs the forward pass (encoding and decoding). Output shape depends on n_repeats and n_features.
- compute_reconstruction_error(inputs, reconstructions=None)[source]¶
Calculates the mean squared error per sample, potentially only over overlapping time steps if input/output lengths differ due to n_repeats.
- Parameters:
inputs (ndarray | Tensor)
reconstructions (ndarray | Tensor | None)
- Return type:
Tensor
Examples
>>> from fusionlab.nn.anomaly_detection import LSTMAutoencoderAnomaly >>> import tensorflow as tf >>> B, T, F = 32, 20, 5 # Batch, TimeSteps, Features >>> inputs = tf.random.normal((B, T, F)) >>> # Instantiate with specific output features and repeats >>> lstm_ae = LSTMAutoencoderAnomaly( ... latent_dim=8, ... lstm_units=16, ... n_features=F, # Explicitly state output features ... n_repeats=T, # Explicitly state output time steps ... num_encoder_layers=2, ... num_decoder_layers=2, ... ) >>> # Get reconstructions >>> reconstructions = lstm_ae(inputs) >>> print(f"Reconstruction shape: {reconstructions.shape}") # Should be (32, 20, 5) TensorShape([32, 20, 5]) >>> # Compute error >>> error = lstm_ae.compute_reconstruction_error(inputs) >>> print(f"Error shape: {error.shape}") # Should be (32,) TensorShape([32])
See also
tensorflow.keras.layers.LayerBase class for Keras layers.
tensorflow.keras.layers.LSTMThe recurrent layer used internally.
tensorflow.keras.layers.RepeatVectorUsed to feed decoder.
tensorflow.keras.layers.TimeDistributedWraps the final Dense layer.
tensorflow.keras.layers.BidirectionalWrapper for bidirectional RNNs.
fusionlab.nn.transformers.XTFTCan potentially incorporate anomaly scores derived from reconstruction errors.
fusionlab.nn.losses.anomaly_lossCan be used with anomaly scores derived from this layer’s error.
SequenceAnomalyScoreLayerAlternative anomaly detection component.
References
- __init__(latent_dim, lstm_units, n_features=None, n_repeats=None, num_encoder_layers=1, num_decoder_layers=1, activation='tanh', intermediate_activation='relu', dropout_rate=0.0, recurrent_dropout_rate=0.0, use_bidirectional_encoder=False, use_bottleneck_dense=False, **kwargs)[source]¶
- Parameters:
latent_dim (int)
lstm_units (int)
n_features (int | None)
n_repeats (int | None)
num_encoder_layers (int)
num_decoder_layers (int)
activation (str)
intermediate_activation (str)
dropout_rate (float)
recurrent_dropout_rate (float)
use_bidirectional_encoder (bool)
use_bottleneck_dense (bool)
Methods
__init__(latent_dim, lstm_units[, ...])add_loss(loss)Can be called inside of the call() method to add a scalar loss.
add_metric(*args, **kwargs)add_variable(shape, initializer[, dtype, ...])Add a weight variable to the layer.
add_weight([shape, initializer, dtype, ...])Add a weight variable to the layer.
build(input_shape)Configure layers whose dimensions depend on input shape.
build_from_config(config)Builds the layer's states with the supplied config dict.
call(inputs[, training])Forward pass: Encode -> [Bottleneck] -> Repeat -> Decode.
compile([optimizer, loss, loss_weights, ...])Configures the model for training.
compile_from_config(config)Compiles the model with the information given in config.
compiled_loss(y, y_pred[, sample_weight, ...])compute_loss([x, y, y_pred, sample_weight, ...])Compute the total loss, validate it, and return it.
compute_mask(inputs, previous_mask)compute_metrics(x, y, y_pred[, sample_weight])Update metric states and collect all metrics to be returned.
compute_output_shape(*args, **kwargs)compute_output_spec(*args, **kwargs)compute_reconstruction_error(inputs[, ...])Computes Mean Squared Error per sample.
count_params()Count the total number of scalars composing the weights.
evaluate([x, y, batch_size, verbose, ...])Returns the loss value & metrics values for the model in test mode.
export(filepath[, format, verbose, ...])Export the model as an artifact for inference.
fit([x, y, batch_size, epochs, verbose, ...])Trains the model for a fixed number of epochs (dataset iterations).
from_config(config)Creates layer from its config.
get_build_config()Returns a dictionary with the layer's input shape.
get_compile_config()Returns a serialized config with information for compiling the model.
Returns the layer configuration.
get_layer([name, index])Retrieves a layer based on either its name (unique) or index.
get_metrics_result()Returns the model's metrics values as a dict.
get_params([deep])Get the parameters for this learner.
get_state_tree([value_format])Retrieves tree-like structure of model variables.
get_weights()Return the values of layer.weights as a list of NumPy arrays.
help(**kwargs)load(file_path[, format])Load the learner's state from a specified file in the desired format.
load_own_variables(store)Loads the state of the layer.
load_weights(filepath[, skip_mismatch])Load the weights from a single file or sharded files.
loss(y, y_pred[, sample_weight])make_predict_function([force])make_test_function([force])make_train_function([force])predict(x[, batch_size, verbose, steps, ...])Generates output predictions for the input samples.
predict_on_batch(x)Returns predictions for a single batch of samples.
predict_step(data)quantize(mode[, config])Quantize the weights of the model.
quantized_build(input_shape, mode)quantized_call(*args, **kwargs)rematerialized_call(layer_call, *args, **kwargs)Enable rematerialization dynamically for layer's call method.
reset_metrics()save(filepath[, overwrite, zipped])Saves a model as a .keras file.
save_own_variables(store)Saves the state of the layer.
save_weights(filepath[, overwrite, ...])Saves all weights to a single file or sharded files.
set_params(**params)Set the parameters of this learner.
set_state_tree(state_tree)Assigns values to variables of the model.
set_weights(weights)Sets the values of layer.weights from a list of NumPy arrays.
stateless_call(trainable_variables, ...[, ...])Call the layer without any side effects.
stateless_compute_loss(trainable_variables, ...)summary([line_length, positions, print_fn, ...])Prints a string summary of the network.
symbolic_call(*args, **kwargs)test_on_batch(x[, y, sample_weight, return_dict])Test the model on a single batch of samples.
test_step(data)to_json(**kwargs)Returns a JSON string containing the network configuration.
train_on_batch(x[, y, sample_weight, ...])Runs a single gradient update on a single batch of data.
train_step(data)Attributes
compiled_metricscompute_dtypeThe dtype of the computations performed by the layer.
distribute_reduction_methoddistribute_strategydtypeAlias of layer.variable_dtype.
dtype_policyinputRetrieves the input tensor(s) of a symbolic operation.
input_dtypeThe dtype layer inputs should be converted to.
input_specjit_compilelayerslossesList of scalar losses from add_loss, regularizers and sublayers.
metricsList of all metrics.
metrics_namesmetrics_variablesList of all metric variables.
non_trainable_variablesList of all non-trainable layer state.
non_trainable_weightsList of all non-trainable weight variables of the layer.
outputRetrieves the output tensor(s) of a layer.
pathThe path of the layer.
quantization_modeThe quantization mode of this layer, None if not quantized.
run_eagerlysupports_maskingWhether this layer supports computing a mask using compute_mask.
trainableSettable boolean, whether this layer should be trainable or not.
trainable_variablesList of all trainable layer state.
trainable_weightsList of all trainable weight variables of the layer.
variable_dtypeThe dtype of the state (weights) of the layer.
variablesList of all layer state, including random seeds.
weightsList of all weight variables of the layer.
- __init__(latent_dim, lstm_units, n_features=None, n_repeats=None, num_encoder_layers=1, num_decoder_layers=1, activation='tanh', intermediate_activation='relu', dropout_rate=0.0, recurrent_dropout_rate=0.0, use_bidirectional_encoder=False, use_bottleneck_dense=False, **kwargs)[source]¶
- Parameters:
latent_dim (int)
lstm_units (int)
n_features (int | None)
n_repeats (int | None)
num_encoder_layers (int)
num_decoder_layers (int)
activation (str)
intermediate_activation (str)
dropout_rate (float)
recurrent_dropout_rate (float)
use_bidirectional_encoder (bool)
use_bottleneck_dense (bool)
- compute_reconstruction_error(inputs, reconstructions=None)[source]¶
Computes Mean Squared Error per sample.
- Parameters:
inputs (ndarray | Tensor)
reconstructions (ndarray | Tensor | None)
- Return type:
Tensor
- help(**kwargs)¶
- my_params = LSTMAutoencoderAnomaly( latent_dim, lstm_units, n_features=None, n_repeats=None, num_encoder_layers=1, num_decoder_layers=1, activation='tanh', intermediate_activation='relu', dropout_rate=0.0, recurrent_dropout_rate=0.0, use_bidirectional_encoder=False, use_bottleneck_dense=False )¶