{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "b518b04cbfe0" }, "source": [ "##### Copyright 2020 The TensorFlow Authors." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "906e07f6e562" }, "outputs": [], "source": [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", "# https://www.apache.org/licenses/LICENSE-2.0\n", "#\n", "# Unless required by applicable law or agreed to in writing, software\n", "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", "# See the License for the specific language governing permissions and\n", "# limitations under the License." ] }, { "cell_type": "markdown", "metadata": { "id": "6ca65cda94c8" }, "source": [ "# Recurrent Neural Networks (RNN) with Keras" ] }, { "cell_type": "markdown", "metadata": { "id": "1e4938db0e55" }, "source": [ "\n", " \n", " \n", " \n", " \n", "
\n", " View on TensorFlow.org\n", " \n", " Run in Google Colab\n", " \n", " View source on GitHub\n", " \n", " Download notebook\n", "
" ] }, { "cell_type": "markdown", "metadata": { "id": "6873211b02d4" }, "source": [ "## Introduction\n", "\n", "Recurrent neural networks (RNN) are a class of neural networks that is powerful for\n", "modeling sequence data such as time series or natural language.\n", "\n", "Schematically, a RNN layer uses a `for` loop to iterate over the timesteps of a\n", "sequence, while maintaining an internal state that encodes information about the\n", "timesteps it has seen so far.\n", "\n", "The Keras RNN API is designed with a focus on:\n", "\n", "- **Ease of use**: the built-in `keras.layers.RNN`, `keras.layers.LSTM`,\n", "`keras.layers.GRU` layers enable you to quickly build recurrent models without\n", "having to make difficult configuration choices.\n", "\n", "- **Ease of customization**: You can also define your own RNN cell layer (the inner\n", "part of the `for` loop) with custom behavior, and use it with the generic\n", "`keras.layers.RNN` layer (the `for` loop itself). This allows you to quickly\n", "prototype different research ideas in a flexible way with minimal code." ] }, { "cell_type": "markdown", "metadata": { "id": "b3600ee25c8e" }, "source": [ "## Setup" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "71c626bbac35" }, "outputs": [], "source": [ "import numpy as np\n", "import tensorflow as tf\n", "from tensorflow import keras\n", "from tensorflow.keras import layers" ] }, { "cell_type": "markdown", "metadata": { "id": "4041a2e9b310" }, "source": [ "## Built-in RNN layers: a simple example" ] }, { "cell_type": "markdown", "metadata": { "id": "98e0c38cf95d" }, "source": [ "There are three built-in RNN layers in Keras:\n", "\n", "1. `keras.layers.SimpleRNN`, a fully-connected RNN where the output from previous\n", "timestep is to be fed to next timestep.\n", "\n", "2. `keras.layers.GRU`, first proposed in\n", "[Cho et al., 2014](https://arxiv.org/abs/1406.1078).\n", "\n", "3. `keras.layers.LSTM`, first proposed in\n", "[Hochreiter & Schmidhuber, 1997](https://www.bioinf.jku.at/publications/older/2604.pdf).\n", "\n", "In early 2015, Keras had the first reusable open-source Python implementations of LSTM\n", "and GRU.\n", "\n", "Here is a simple example of a `Sequential` model that processes sequences of integers,\n", "embeds each integer into a 64-dimensional vector, then processes the sequence of\n", "vectors using a `LSTM` layer." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "a5617759e54e" }, "outputs": [], "source": [ "model = keras.Sequential()\n", "# Add an Embedding layer expecting input vocab of size 1000, and\n", "# output embedding dimension of size 64.\n", "model.add(layers.Embedding(input_dim=1000, output_dim=64))\n", "\n", "# Add a LSTM layer with 128 internal units.\n", "model.add(layers.LSTM(128))\n", "\n", "# Add a Dense layer with 10 units.\n", "model.add(layers.Dense(10))\n", "\n", "model.summary()" ] }, { "cell_type": "markdown", "metadata": { "id": "cb8ef33660a0" }, "source": [ "Built-in RNNs support a number of useful features:\n", "\n", "- Recurrent dropout, via the `dropout` and `recurrent_dropout` arguments\n", "- Ability to process an input sequence in reverse, via the `go_backwards` argument\n", "- Loop unrolling (which can lead to a large speedup when processing short sequences on\n", "CPU), via the `unroll` argument\n", "- ...and more.\n", "\n", "For more information, see the\n", "[RNN API documentation](https://keras.io/api/layers/recurrent_layers/)." ] }, { "cell_type": "markdown", "metadata": { "id": "43aa4e4f344d" }, "source": [ "## Outputs and states\n", "\n", "By default, the output of a RNN layer contains a single vector per sample. This vector\n", "is the RNN cell output corresponding to the last timestep, containing information\n", "about the entire input sequence. The shape of this output is `(batch_size, units)`\n", "where `units` corresponds to the `units` argument passed to the layer's constructor.\n", "\n", "A RNN layer can also return the entire sequence of outputs for each sample (one vector\n", "per timestep per sample), if you set `return_sequences=True`. The shape of this output\n", "is `(batch_size, timesteps, units)`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "c3294dec91e4" }, "outputs": [], "source": [ "model = keras.Sequential()\n", "model.add(layers.Embedding(input_dim=1000, output_dim=64))\n", "\n", "# The output of GRU will be a 3D tensor of shape (batch_size, timesteps, 256)\n", "model.add(layers.GRU(256, return_sequences=True))\n", "\n", "# The output of SimpleRNN will be a 2D tensor of shape (batch_size, 128)\n", "model.add(layers.SimpleRNN(128))\n", "\n", "model.add(layers.Dense(10))\n", "\n", "model.summary()" ] }, { "cell_type": "markdown", "metadata": { "id": "266812a04bb2" }, "source": [ "In addition, a RNN layer can return its final internal state(s). The returned states\n", "can be used to resume the RNN execution later, or\n", "[to initialize another RNN](https://arxiv.org/abs/1409.3215).\n", "This setting is commonly used in the\n", "encoder-decoder sequence-to-sequence model, where the encoder final state is used as\n", "the initial state of the decoder.\n", "\n", "To configure a RNN layer to return its internal state, set the `return_state` parameter\n", "to `True` when creating the layer. Note that `LSTM` has 2 state tensors, but `GRU`\n", "only has one.\n", "\n", "To configure the initial state of the layer, just call the layer with additional\n", "keyword argument `initial_state`.\n", "Note that the shape of the state needs to match the unit size of the layer, like in the\n", "example below." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "ece412e6afbe" }, "outputs": [], "source": [ "encoder_vocab = 1000\n", "decoder_vocab = 2000\n", "\n", "encoder_input = layers.Input(shape=(None,))\n", "encoder_embedded = layers.Embedding(input_dim=encoder_vocab, output_dim=64)(\n", " encoder_input\n", ")\n", "\n", "# Return states in addition to output\n", "output, state_h, state_c = layers.LSTM(64, return_state=True, name=\"encoder\")(\n", " encoder_embedded\n", ")\n", "encoder_state = [state_h, state_c]\n", "\n", "decoder_input = layers.Input(shape=(None,))\n", "decoder_embedded = layers.Embedding(input_dim=decoder_vocab, output_dim=64)(\n", " decoder_input\n", ")\n", "\n", "# Pass the 2 states to a new LSTM layer, as initial state\n", "decoder_output = layers.LSTM(64, name=\"decoder\")(\n", " decoder_embedded, initial_state=encoder_state\n", ")\n", "output = layers.Dense(10)(decoder_output)\n", "\n", "model = keras.Model([encoder_input, decoder_input], output)\n", "model.summary()" ] }, { "cell_type": "markdown", "metadata": { "id": "e97a845a372a" }, "source": [ "## RNN layers and RNN cells\n", "\n", "In addition to the built-in RNN layers, the RNN API also provides cell-level APIs.\n", "Unlike RNN layers, which processes whole batches of input sequences, the RNN cell only\n", "processes a single timestep.\n", "\n", "The cell is the inside of the `for` loop of a RNN layer. Wrapping a cell inside a\n", "`keras.layers.RNN` layer gives you a layer capable of processing batches of\n", "sequences, e.g. `RNN(LSTMCell(10))`.\n", "\n", "Mathematically, `RNN(LSTMCell(10))` produces the same result as `LSTM(10)`. In fact,\n", "the implementation of this layer in TF v1.x was just creating the corresponding RNN\n", "cell and wrapping it in a RNN layer. However using the built-in `GRU` and `LSTM`\n", "layers enable the use of CuDNN and you may see better performance.\n", "\n", "There are three built-in RNN cells, each of them corresponding to the matching RNN\n", "layer.\n", "\n", "- `keras.layers.SimpleRNNCell` corresponds to the `SimpleRNN` layer.\n", "\n", "- `keras.layers.GRUCell` corresponds to the `GRU` layer.\n", "\n", "- `keras.layers.LSTMCell` corresponds to the `LSTM` layer.\n", "\n", "The cell abstraction, together with the generic `keras.layers.RNN` class, make it\n", "very easy to implement custom RNN architectures for your research." ] }, { "cell_type": "markdown", "metadata": { "id": "60b3b721d500" }, "source": [ "## Cross-batch statefulness\n", "\n", "When processing very long sequences (possibly infinite), you may want to use the\n", "pattern of **cross-batch statefulness**.\n", "\n", "Normally, the internal state of a RNN layer is reset every time it sees a new batch\n", "(i.e. every sample seen by the layer is assumed to be independent of the past). The\n", "layer will only maintain a state while processing a given sample.\n", "\n", "If you have very long sequences though, it is useful to break them into shorter\n", "sequences, and to feed these shorter sequences sequentially into a RNN layer without\n", "resetting the layer's state. That way, the layer can retain information about the\n", "entirety of the sequence, even though it's only seeing one sub-sequence at a time.\n", "\n", "You can do this by setting `stateful=True` in the constructor.\n", "\n", "If you have a sequence `s = [t0, t1, ... t1546, t1547]`, you would split it into e.g.\n", "\n", "```\n", "s1 = [t0, t1, ... t100]\n", "s2 = [t101, ... t201]\n", "...\n", "s16 = [t1501, ... t1547]\n", "```\n", "\n", "Then you would process it via:\n", "\n", "```python\n", "lstm_layer = layers.LSTM(64, stateful=True)\n", "for s in sub_sequences:\n", " output = lstm_layer(s)\n", "```\n", "\n", "When you want to clear the state, you can use `layer.reset_states()`.\n", "\n", "\n", "> Note: In this setup, sample `i` in a given batch is assumed to be the continuation of\n", "sample `i` in the previous batch. This means that all batches should contain the same\n", "number of samples (batch size). E.g. if a batch contains `[sequence_A_from_t0_to_t100,\n", " sequence_B_from_t0_to_t100]`, the next batch should contain\n", "`[sequence_A_from_t101_to_t200, sequence_B_from_t101_to_t200]`.\n", "\n", "\n", "\n", "\n", "Here is a complete example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "19e72be49a42" }, "outputs": [], "source": [ "paragraph1 = np.random.random((20, 10, 50)).astype(np.float32)\n", "paragraph2 = np.random.random((20, 10, 50)).astype(np.float32)\n", "paragraph3 = np.random.random((20, 10, 50)).astype(np.float32)\n", "\n", "lstm_layer = layers.LSTM(64, stateful=True)\n", "output = lstm_layer(paragraph1)\n", "output = lstm_layer(paragraph2)\n", "output = lstm_layer(paragraph3)\n", "\n", "# reset_states() will reset the cached state to the original initial_state.\n", "# If no initial_state was provided, zero-states will be used by default.\n", "lstm_layer.reset_states()\n" ] }, { "cell_type": "markdown", "metadata": { "id": "ec7c316b19a1" }, "source": [ "### RNN State Reuse\n", "" ] }, { "cell_type": "markdown", "metadata": { "id": "3cb7a8ac464a" }, "source": [ "The recorded states of the RNN layer are not included in the `layer.weights()`. If you\n", "would like to reuse the state from a RNN layer, you can retrieve the states value by\n", "`layer.states` and use it as the\n", "initial state for a new layer via the Keras functional API like `new_layer(inputs,\n", "initial_state=layer.states)`, or model subclassing.\n", "\n", "Please also note that sequential model might not be used in this case since it only\n", "supports layers with single input and output, the extra input of initial state makes\n", "it impossible to use here." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "009c5b393adf" }, "outputs": [], "source": [ "paragraph1 = np.random.random((20, 10, 50)).astype(np.float32)\n", "paragraph2 = np.random.random((20, 10, 50)).astype(np.float32)\n", "paragraph3 = np.random.random((20, 10, 50)).astype(np.float32)\n", "\n", "lstm_layer = layers.LSTM(64, stateful=True)\n", "output = lstm_layer(paragraph1)\n", "output = lstm_layer(paragraph2)\n", "\n", "existing_state = lstm_layer.states\n", "\n", "new_lstm_layer = layers.LSTM(64)\n", "new_output = new_lstm_layer(paragraph3, initial_state=existing_state)\n" ] }, { "cell_type": "markdown", "metadata": { "id": "66c1d7f1ccba" }, "source": [ "## Bidirectional RNNs\n", "\n", "For sequences other than time series (e.g. text), it is often the case that a RNN model\n", "can perform better if it not only processes sequence from start to end, but also\n", "backwards. For example, to predict the next word in a sentence, it is often useful to\n", "have the context around the word, not only just the words that come before it.\n", "\n", "Keras provides an easy API for you to build such bidirectional RNNs: the\n", "`keras.layers.Bidirectional` wrapper." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "8cea1781a0c2" }, "outputs": [], "source": [ "model = keras.Sequential()\n", "\n", "model.add(\n", " layers.Bidirectional(layers.LSTM(64, return_sequences=True), input_shape=(5, 10))\n", ")\n", "model.add(layers.Bidirectional(layers.LSTM(32)))\n", "model.add(layers.Dense(10))\n", "\n", "model.summary()" ] }, { "cell_type": "markdown", "metadata": { "id": "dab57c97a566" }, "source": [ "Under the hood, `Bidirectional` will copy the RNN layer passed in, and flip the\n", "`go_backwards` field of the newly copied layer, so that it will process the inputs in\n", "reverse order.\n", "\n", "The output of the `Bidirectional` RNN will be, by default, the concatenation of the forward layer\n", "output and the backward layer output. If you need a different merging behavior, e.g.\n", "concatenation, change the `merge_mode` parameter in the `Bidirectional` wrapper\n", "constructor. For more details about `Bidirectional`, please check\n", "[the API docs](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Bidirectional/)." ] }, { "cell_type": "markdown", "metadata": { "id": "18a254dfaa73" }, "source": [ "## Performance optimization and CuDNN kernels\n", "\n", "In TensorFlow 2.0, the built-in LSTM and GRU layers have been updated to leverage CuDNN\n", "kernels by default when a GPU is available. With this change, the prior\n", "`keras.layers.CuDNNLSTM/CuDNNGRU` layers have been deprecated, and you can build your\n", "model without worrying about the hardware it will run on.\n", "\n", "Since the CuDNN kernel is built with certain assumptions, this means the layer **will\n", "not be able to use the CuDNN kernel if you change the defaults of the built-in LSTM or\n", "GRU layers**. E.g.:\n", "\n", "- Changing the `activation` function from `tanh` to something else.\n", "- Changing the `recurrent_activation` function from `sigmoid` to something else.\n", "- Using `recurrent_dropout` > 0.\n", "- Setting `unroll` to True, which forces LSTM/GRU to decompose the inner\n", "`tf.while_loop` into an unrolled `for` loop.\n", "- Setting `use_bias` to False.\n", "- Using masking when the input data is not strictly right padded (if the mask\n", "corresponds to strictly right padded data, CuDNN can still be used. This is the most\n", "common case).\n", "\n", "For the detailed list of constraints, please see the documentation for the\n", "[LSTM](https://www.tensorflow.org/api_docs/python/tf/keras/layers/LSTM/) and\n", "[GRU](https://www.tensorflow.org/api_docs/python/tf/keras/layers/GRU/) layers." ] }, { "cell_type": "markdown", "metadata": { "id": "fb8de09c4343" }, "source": [ "### Using CuDNN kernels when available\n", "\n", "Let's build a simple LSTM model to demonstrate the performance difference.\n", "\n", "We'll use as input sequences the sequence of rows of MNIST digits (treating each row of\n", "pixels as a timestep), and we'll predict the digit's label." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "e88aab9e73c7" }, "outputs": [], "source": [ "batch_size = 64\n", "# Each MNIST image batch is a tensor of shape (batch_size, 28, 28).\n", "# Each input sequence will be of size (28, 28) (height is treated like time).\n", "input_dim = 28\n", "\n", "units = 64\n", "output_size = 10 # labels are from 0 to 9\n", "\n", "# Build the RNN model\n", "def build_model(allow_cudnn_kernel=True):\n", " # CuDNN is only available at the layer level, and not at the cell level.\n", " # This means `LSTM(units)` will use the CuDNN kernel,\n", " # while RNN(LSTMCell(units)) will run on non-CuDNN kernel.\n", " if allow_cudnn_kernel:\n", " # The LSTM layer with default options uses CuDNN.\n", " lstm_layer = keras.layers.LSTM(units, input_shape=(None, input_dim))\n", " else:\n", " # Wrapping a LSTMCell in a RNN layer will not use CuDNN.\n", " lstm_layer = keras.layers.RNN(\n", " keras.layers.LSTMCell(units), input_shape=(None, input_dim)\n", " )\n", " model = keras.models.Sequential(\n", " [\n", " lstm_layer,\n", " keras.layers.BatchNormalization(),\n", " keras.layers.Dense(output_size),\n", " ]\n", " )\n", " return model\n" ] }, { "cell_type": "markdown", "metadata": { "id": "dcde82cb14d6" }, "source": [ "Let's load the MNIST dataset:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "98292f8e71a9" }, "outputs": [], "source": [ "mnist = keras.datasets.mnist\n", "\n", "(x_train, y_train), (x_test, y_test) = mnist.load_data()\n", "x_train, x_test = x_train / 255.0, x_test / 255.0\n", "sample, sample_label = x_train[0], y_train[0]" ] }, { "cell_type": "markdown", "metadata": { "id": "443e5458284f" }, "source": [ "Let's create a model instance and train it.\n", "\n", "We choose `sparse_categorical_crossentropy` as the loss function for the model. The\n", "output of the model has shape of `[batch_size, 10]`. The target for the model is an\n", "integer vector, each of the integer is in the range of 0 to 9." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "f85b57b010e5" }, "outputs": [], "source": [ "model = build_model(allow_cudnn_kernel=True)\n", "\n", "model.compile(\n", " loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n", " optimizer=\"sgd\",\n", " metrics=[\"accuracy\"],\n", ")\n", "\n", "\n", "model.fit(\n", " x_train, y_train, validation_data=(x_test, y_test), batch_size=batch_size, epochs=1\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "99ea5495e375" }, "source": [ "Now, let's compare to a model that does not use the CuDNN kernel:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "d4bdff02e617" }, "outputs": [], "source": [ "noncudnn_model = build_model(allow_cudnn_kernel=False)\n", "noncudnn_model.set_weights(model.get_weights())\n", "noncudnn_model.compile(\n", " loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n", " optimizer=\"sgd\",\n", " metrics=[\"accuracy\"],\n", ")\n", "noncudnn_model.fit(\n", " x_train, y_train, validation_data=(x_test, y_test), batch_size=batch_size, epochs=1\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "90fc64fbd4ea" }, "source": [ "When running on a machine with a NVIDIA GPU and CuDNN installed,\n", "the model built with CuDNN is much faster to train compared to the\n", "model that uses the regular TensorFlow kernel.\n", "\n", "The same CuDNN-enabled model can also be used to run inference in a CPU-only\n", "environment. The `tf.device` annotation below is just forcing the device placement.\n", "The model will run on CPU by default if no GPU is available.\n", "\n", "You simply don't have to worry about the hardware you're running on anymore. Isn't that\n", "pretty cool?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "7e33c62b6029" }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "\n", "with tf.device(\"CPU:0\"):\n", " cpu_model = build_model(allow_cudnn_kernel=True)\n", " cpu_model.set_weights(model.get_weights())\n", " result = tf.argmax(cpu_model.predict_on_batch(tf.expand_dims(sample, 0)), axis=1)\n", " print(\n", " \"Predicted result is: %s, target result is: %s\" % (result.numpy(), sample_label)\n", " )\n", " plt.imshow(sample, cmap=plt.get_cmap(\"gray\"))" ] }, { "cell_type": "markdown", "metadata": { "id": "2f940b73a2a6" }, "source": [ "## RNNs with list/dict inputs, or nested inputs\n", "\n", "Nested structures allow implementers to include more information within a single\n", "timestep. For example, a video frame could have audio and video input at the same\n", "time. The data shape in this case could be:\n", "\n", "`[batch, timestep, {\"video\": [height, width, channel], \"audio\": [frequency]}]`\n", "\n", "In another example, handwriting data could have both coordinates x and y for the\n", "current position of the pen, as well as pressure information. So the data\n", "representation could be:\n", "\n", "`[batch, timestep, {\"location\": [x, y], \"pressure\": [force]}]`\n", "\n", "The following code provides an example of how to build a custom RNN cell that accepts\n", "such structured inputs." ] }, { "cell_type": "markdown", "metadata": { "id": "f78dc4c1c516" }, "source": [ "### Define a custom cell that supports nested input/output" ] }, { "cell_type": "markdown", "metadata": { "id": "199faf57f0c5" }, "source": [ "See [Making new Layers & Models via subclassing](https://www.tensorflow.org/guide/keras/custom_layers_and_models/)\n", "for details on writing your own layers." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "451cfd5f0cc4" }, "outputs": [], "source": [ "class NestedCell(keras.layers.Layer):\n", " def __init__(self, unit_1, unit_2, unit_3, **kwargs):\n", " self.unit_1 = unit_1\n", " self.unit_2 = unit_2\n", " self.unit_3 = unit_3\n", " self.state_size = [tf.TensorShape([unit_1]), tf.TensorShape([unit_2, unit_3])]\n", " self.output_size = [tf.TensorShape([unit_1]), tf.TensorShape([unit_2, unit_3])]\n", " super(NestedCell, self).__init__(**kwargs)\n", "\n", " def build(self, input_shapes):\n", " # expect input_shape to contain 2 items, [(batch, i1), (batch, i2, i3)]\n", " i1 = input_shapes[0][1]\n", " i2 = input_shapes[1][1]\n", " i3 = input_shapes[1][2]\n", "\n", " self.kernel_1 = self.add_weight(\n", " shape=(i1, self.unit_1), initializer=\"uniform\", name=\"kernel_1\"\n", " )\n", " self.kernel_2_3 = self.add_weight(\n", " shape=(i2, i3, self.unit_2, self.unit_3),\n", " initializer=\"uniform\",\n", " name=\"kernel_2_3\",\n", " )\n", "\n", " def call(self, inputs, states):\n", " # inputs should be in [(batch, input_1), (batch, input_2, input_3)]\n", " # state should be in shape [(batch, unit_1), (batch, unit_2, unit_3)]\n", " input_1, input_2 = tf.nest.flatten(inputs)\n", " s1, s2 = states\n", "\n", " output_1 = tf.matmul(input_1, self.kernel_1)\n", " output_2_3 = tf.einsum(\"bij,ijkl->bkl\", input_2, self.kernel_2_3)\n", " state_1 = s1 + output_1\n", " state_2_3 = s2 + output_2_3\n", "\n", " output = (output_1, output_2_3)\n", " new_states = (state_1, state_2_3)\n", "\n", " return output, new_states\n", "\n", " def get_config(self):\n", " return {\"unit_1\": self.unit_1, \"unit_2\": unit_2, \"unit_3\": self.unit_3}\n" ] }, { "cell_type": "markdown", "metadata": { "id": "51355b4089d2" }, "source": [ "### Build a RNN model with nested input/output\n", "\n", "Let's build a Keras model that uses a `keras.layers.RNN` layer and the custom cell\n", "we just defined." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "b2eba7a248eb" }, "outputs": [], "source": [ "unit_1 = 10\n", "unit_2 = 20\n", "unit_3 = 30\n", "\n", "i1 = 32\n", "i2 = 64\n", "i3 = 32\n", "batch_size = 64\n", "num_batches = 10\n", "timestep = 50\n", "\n", "cell = NestedCell(unit_1, unit_2, unit_3)\n", "rnn = keras.layers.RNN(cell)\n", "\n", "input_1 = keras.Input((None, i1))\n", "input_2 = keras.Input((None, i2, i3))\n", "\n", "outputs = rnn((input_1, input_2))\n", "\n", "model = keras.models.Model([input_1, input_2], outputs)\n", "\n", "model.compile(optimizer=\"adam\", loss=\"mse\", metrics=[\"accuracy\"])" ] }, { "cell_type": "markdown", "metadata": { "id": "452a99c63b7c" }, "source": [ "### Train the model with randomly generated data\n", "\n", "Since there isn't a good candidate dataset for this model, we use random Numpy data for\n", "demonstration." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "3987993cb7be" }, "outputs": [], "source": [ "input_1_data = np.random.random((batch_size * num_batches, timestep, i1))\n", "input_2_data = np.random.random((batch_size * num_batches, timestep, i2, i3))\n", "target_1_data = np.random.random((batch_size * num_batches, unit_1))\n", "target_2_data = np.random.random((batch_size * num_batches, unit_2, unit_3))\n", "input_data = [input_1_data, input_2_data]\n", "target_data = [target_1_data, target_2_data]\n", "\n", "model.fit(input_data, target_data, batch_size=batch_size)" ] }, { "cell_type": "markdown", "metadata": { "id": "b51e87780b0f" }, "source": [ "With the Keras `keras.layers.RNN` layer, You are only expected to define the math\n", "logic for individual step within the sequence, and the `keras.layers.RNN` layer\n", "will handle the sequence iteration for you. It's an incredibly powerful way to quickly\n", "prototype new kinds of RNNs (e.g. a LSTM variant).\n", "\n", "For more details, please visit the [API docs](https://https://www.tensorflow.org/api_docs/python/tf/keras/layers/RNN/)." ] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "rnn.ipynb", "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }