Open In App

Tensorflow.js tf.layers.rnn() Function

Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. 

Tensorflow.js tf.layers.rnn() function is basically base class for recurrent layers. 



Syntax:

tf.layers.rnn( args );

Parameters: 



Return Value: It returns RNN.

This layer supports masking for input data with any number of timesteps. We can set RNN layers to be ‘stateful’, which means that the state computed for the samples in one batch will be reused as initial states for the next batch. 

Input shape should be a 3D tensor with shape [ batchSize, timeSteps, inputDim ]

As per the parameters and values provide to this layer we get the shape of the output layer: 

Example 1: If returnState is set true then this function return array of tensor in which the first tensor is the output. the remaining tensors are the state at the last time steps. The Shape of all the tensors in the array will be [ batchSize, units].




// Cells for RNN
const cells = [
   tf.layers.lstmCell({units: 4}),
   tf.layers.lstmCell({units: 8}),
];
const rnn = tf.layers.rnn({cell: cells, returnState:true });
 
// Create an input with 8 time steps and
// 16 length vector at each step.
const Input_layer = tf.input({shape: [8, 16]});
const Output_layer = rnn.apply(Input_layer);
 
console.log(JSON.stringify(Output_layer[0].shape));

Output:

​[null, 8]

Example 2: If returnState is not set and returnSequence is set to true then the Output tensor will have the shape: [ batchSize, timeSteps, units ].




// Cells for RNN
const cells = [
    tf.layers.lstmCell({units: 16}),
    tf.layers.lstmCell({units: 32}),
];
const rnn = tf.layers.rnn({
    cell: cells,
    returnState: false,
    returnSequences: true
});
 
// Create an input with 8 time steps and
// 16 length vector at each step.
const Input_layer = tf.input({shape: [4, 8]});
const Output_layer = rnn.apply(Input_layer);
console.log(JSON.stringify(Output_layer.shape));

Output:

[null,4,32]

Example 3: If both returnState and returnSequences are not defined then the shape of output will be [ batchSize, units ].




// Cells for RNN
const cells = [
   tf.layers.lstmCell({units: 4}),
   tf.layers.lstmCell({units: 8}),
];
const rnn = tf.layers.rnn({cell: cells});
 
// Create an input with 10 time steps and
// 20 length vector at each step.
const input = tf.input({shape: [10, 20]});
const output = rnn.apply(input);
 
console.log(JSON.stringify(output.shape));

Output:

[null,8]

References: https://js.tensorflow.org/api/latest/#layers.rnn


Article Tags :