In a previous tutorial series I went over some of the theory behind Recurrent Neural Networks (RNNs) and the implementation of a simple RNN from scratch. That’s a useful exercise, but in practice we use libraries like Tensorflow with high-level primitives for dealing with RNNs.
With that using an RNN should be as easy as calling a function, right? Unfortunately that’s not quite the case. In this post I want to go over some of the best practices for working with RNNs in Tensorflow, especially the functionality that isn’t well documented on the official site.
The post comes with a Github repository that contains Jupyter notebooks with minimal examples for: Using tf.SequenceExample Batching and Padding Dynamic RNN Bidirectional Dynamic RNN RNN Cells and Cell Wrappers Masking the Loss
Preprocessing Data: Use tf.SequenceExample
Check out the tf.SequenceExample Jupyter Notebook here!
RNNs are used for sequential data that has inputs and/or outputs at multiple time steps. Tensorflow comes with a protocol buffer definition to deal with such data: tf.SequenceExample.
You can load data directly from your Python/Numpy arrays, but it’s probably in your best interest to use tf.SequenceExample instead. This data structure consists of a “context” for non-sequential features and “feature_lists” for sequential features. It’s somewhat verbose (it blew up my latest dataset by 10x), but it comes with a few benefits that are worth it: Easy distributed training. Split up data into multiple TFRecord files, each containing many SequenceExamples, and use Tensorflow’s built-in support for distributed training. Reusability. Other people can re-use your model by bringing their own data into tf.SequenceExample format. No model code changes required. Use of Tensorflow data loading pipelines functions like tf.parse_single_sequence_example. Libraries like tf.learn also come with convenience function that expect you to feed data in protocol buffer format. Separation of data preprocessing and model code. Using tf.SequenceExample forces you to separate your data preprocessing and Tensorflow model code. This is good practice, as your model shouldn’t make any assumptions about the input data it gets.
In practice, you write a little script that converts your data into tf.SequenceExample format and then writes one or more TFRecord files. These TFRecord files are parsed by Tensorflow to become the input to your model: Convert your data into tf.SequenceExample format Write one or more TFRecord files with the serialized data Use tf.TFRecordReader to read examples from the file Parse each example using tf.parse_single_sequence_example (Not in the official docs yet)
| sequences = [[ 1 , 2 , 3 ], [ 4 , 5 , 1 ], [ 1 , 2 ]] label_sequences = [[ 0 , 1 , 0 ], [ 1 , 0 |