A Gentle Introduction To LSTM Autoencoders
A Gentle Introduction To LSTM Autoencoders
Search...
Once fit, the encoder part of the model can be used to encode or compress sequence data that in
turn may be used in data visualizations or as a feature vector input to a supervised learning model.
In this post, you will discover the LSTM Autoencoder model and how to implement it in Python using
Keras.
Autoencoders are a type of self-supervised learning model that can learn a compressed
representation of input data.
LSTM Autoencoders can learn a compressed representation of sequence data and have been
used on video, text, audio, and time series sequence data.
How to develop LSTM Autoencoder models in Python using the Keras deep learning library.
Kick-start your project with my new book Long Short-Term Memory Networks With Python,
including step-by-step tutorials and the Python source code files for all examples.
Overview
This post is divided into six sections; they are:
They are an unsupervised learning method, although technically, they are trained using supervised
learning methods, referred to as self-supervised. They are typically trained as part of a broader
model that attempts to recreate the input.
For example:
1 X = model.predict(X)
The design of the autoencoder model purposefully makes this challenging by restricting the
architecture to a bottleneck at the midpoint of the model, from which the reconstruction of the input
data is performed.
There are many types of autoencoders, and their use varies, but perhaps the more common use is
as a learned or automatic feature extraction model.
In this case, once the model is fit, the reconstruction aspect of the model can be discarded and the
model up to the point of the bottleneck can be used. The output of the model at the bottleneck is a
fixed length vector that provides a compressed representation of the input data.
Input data from the domain can then be provided to the model and the output of the model at the
bottleneck can be used as a feature vector in a supervised learning model, for visualization, or more
generally for dimensionality reduction.
This is challenging because machine learning algorithms, and neural networks in particular, are
designed to work with fixed length inputs.
Another challenge with sequence data is that the temporal ordering of the observations can make it
challenging to extract features suitable for use as input to supervised learning models, often requiring
deep expertise in the domain or in the field of signal processing.
Finally, many predictive modeling problems involving sequences require a prediction that itself is also
a sequence. These are called sequence-to-sequence, or seq2seq, prediction problems.
They are capable of learning the complex dynamics within the temporal ordering of input sequences
as well as use an internal memory to remember or use information across long input sequences.
The LSTM network can be organized into an architecture called the Encoder-Decoder LSTM that
allows the model to be used to both support variable length input sequences and to predict or output
variable length output sequences.
This architecture is the basis for many advances in complex sequence prediction problems such as
speech recognition and text translation.
In this architecture, an encoder LSTM model reads the input sequence step-by-step. After reading in
the entire input sequence, the hidden state or output of this model represents an internal learned
representation of the entire input sequence as a fixed-length vector. This vector is then provided as
an input to the decoder model that interprets it as each step in the output sequence is generated.
For a given dataset of sequences, an encoder-decoder LSTM is configured to read the input
sequence, encode it, decode it, and recreate it. The performance of the model is evaluated based on
the model’s ability to recreate the input sequence.
Once the model achieves a desired level of performance recreating the sequence, the decoder part
of the model may be removed, leaving just the encoder model. This model can then be used to
encode input sequences to a fixed-length vector.
The resulting vectors can then be used in a variety of applications, not least as a compressed
representation of the sequence as an input to another supervised learning model.
In the paper, Nitish Srivastava, et al. describe the LSTM Autoencoder as an extension or application
of the Encoder-Decoder LSTM.
They use the model with video input data to both reconstruct sequences of frames of video as well
as to predict frames of video, both of which are described as an unsupervised learning task.
The input to the model is a sequence of vectors (image patches or features). The encoder
LSTM reads in this sequence. After the last input has been read, the decoder LSTM takes
over and outputs a prediction for the target sequence.
More than simply using the model directly, the authors explore some interesting architecture choices
that may help inform future applications of the model.
They designed the model in such a way as to recreate the target sequence of video frames in
reverse order, claiming that it makes the optimization problem solved by the model more tractable.
The target sequence is same as the input sequence, but in reverse order. Reversing the
target sequence makes the optimization easier because the model can get off the ground
by looking at low range correlations.
They also explore two approaches to training the decoder model, specifically a version conditioned in
the previous output generated by the decoder, and another without any such conditioning.
A more elaborate autoencoder model was also explored where two decoder models were used for
the one encoder: one to predict the next frame in the sequence and one to reconstruct frames in the
sequence, referred to as a composite model.
… reconstructing the input and predicting the future can be combined to create a
composite […]. Here the encoder LSTM is asked to come up with a state from which we
can both predict the next few frames as well as reconstruct the input.
The models were evaluated in many ways, including using encoder to seed a classifier. It appears
that rather than using the output of the encoder as an input for classification, they chose to seed a
standalone LSTM classifier with the weights of the encoder model directly. This is surprising given
the complication of the implementation.
We initialize an LSTM classifier with the weights learned by the encoder LSTM from this
model.
The composite model without conditioning on the decoder was found to perform the best in their
experiments.
The best performing model was the Composite Model that combined an autoencoder and
a future predictor. The conditional variants did not give any significant improvements in
terms of classification accuracy after fine-tuning, however they did give slightly lower
prediction errors.
Many other applications of the LSTM Autoencoder have been demonstrated, not least with
sequences of text, audio data and time series.
For these demonstrations, we will use a dataset of one sample of nine time steps and one feature:
We can start-off by defining the sequence and reshaping it into the preferred shape of [samples,
timesteps, features].
Next, we can define the encoder-decoder LSTM architecture that expects input sequences with nine
time steps and one feature and outputs a sequence with nine time steps and one feature.
1 # define model
2 model = Sequential()
3 model.add(LSTM(100, activation='relu', input_shape=(n_in,1)))
4 model.add(RepeatVector(n_in))
5 model.add(LSTM(100, activation='relu', return_sequences=True))
6 model.add(TimeDistributed(Dense(1)))
7 model.compile(optimizer='adam', loss='mse')
1 # fit model
2 model.fit(sequence, sequence, epochs=300, verbose=0)
The complete example is listed below.
The configuration of the model, such as the number of units and training epochs, was completely
arbitrary.
Running the example fits the autoencoder and prints the reconstructed input sequence.
Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or
differences in numerical precision. Consider running the example a few times and compare the
average outcome.
The results are close enough, with very minor rounding errors.
In the case of our small contrived problem, we expect the output to be the sequence:
This means that the model will expect each input sequence to have nine time steps and the output
sequence to have eight time steps.
Running the example prints the output sequence that predicts the next time step for each input time
step.
Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or
differences in numerical precision. Consider running the example a few times and compare the
average outcome.
We can see that the model is accurate, barring some minor rounding errors.
We can implement this multi-output model in Keras using the functional API. You can learn more
about the functional API in this post:
1 # define encoder
2 visible = Input(shape=(n_in,1))
3 encoder = LSTM(100, activation='relu')(visible)
1 # tie it together
2 model = Model(inputs=visible, outputs=[decoder1, decoder2])
Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or
differences in numerical precision. Consider running the example a few times and compare the
average outcome.
Running the example both reconstructs and predicts the output sequence, using both decoders.
1 [array([[[0.10736275],
2 [0.20335874],
3 [0.30020815],
4 [0.3983948 ],
5 [0.4985725 ],
6 [0.5998295 ],
7 [0.700336 ,
8 [0.8001949 ],
9 [0.89984304]]], dtype=float32),
10
11 array([[[0.16298929],
12 [0.28785267],
13 [0.4030449 ],
14 [0.5104638 ],
15 [0.61162543],
16 [0.70776784],
17 [0.79992455],
18 [0.8889787 ]]], dtype=float32)]
The encoder can then be used to transform input sequences to a fixed length encoded vector.
We can do this by creating a new model that has the same inputs as our original model, and outputs
directly from the end of encoder model, before the RepeatVector layer.
A complete example of doing this with the reconstruction LSTM autoencoder is listed below.
1 # lstm autoencoder recreate sequence
2 from numpy import array
3 from keras.models import Sequential
4 from keras.models import Model
5 from keras.layers import LSTM
6 from keras.layers import Dense
7 from keras.layers import RepeatVector
8 from keras.layers import TimeDistributed
9 from keras.utils import plot_model
10 # define input sequence
11 sequence = array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
12 # reshape input into [samples, timesteps, features]
13 n_in = len(sequence)
14 sequence = sequence.reshape((1, n_in, 1))
15 # define model
16 model = Sequential()
17 model.add(LSTM(100, activation='relu', input_shape=(n_in,1)))
18 model.add(RepeatVector(n_in))
19 model.add(LSTM(100, activation='relu', return_sequences=True))
20 model.add(TimeDistributed(Dense(1)))
21 model.compile(optimizer='adam', loss='mse')
22 # fit model
23 model.fit(sequence, sequence, epochs=300, verbose=0)
24 # connect the encoder LSTM as the output layer
25 model = Model(inputs=model.inputs, outputs=model.layers[0].output)
26 plot_model(model, show_shapes=True, to_file='lstm_encoder.png')
27 # get the feature vector for the input sequence
28 yhat = model.predict(sequence)
29 print(yhat.shape)
30 print(yhat)
Running the example creates a standalone encoder model that could be used or saved for later use.
We demonstrate the encoder by predicting the sequence and getting back the 100 element output of
the encoder.
Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or
differences in numerical precision. Consider running the example a few times and compare the
average outcome.
Further Reading
This section provides more resources on the topic if you are looking to go deeper.
Summary
In this post, you discovered the LSTM Autoencoder model and how to implement it in Python using
Keras.
Autoencoders are a type of self-supervised learning model that can learn a compressed
representation of input data.
LSTM Autoencoders can learn a compressed representation of sequence data and have been
used on video, text, audio, and time series sequence data.
How to develop LSTM Autoencoder models in Python using the Keras deep learning library.