Open In App

Tensorflow.js tf.layers.stackedRNNCells() Function

Introduction: 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.stackedRNNCells() function is used to stack the RNN cell and make them to behave as a single cell. 



Syntax:

tf.layers.stackedRNNCells(arge); 

Parameters: Above method accepts the following parameter:



Returns: It returns an object (StackedRNNCells).

Example 1: In this example, we will see how simple RNNCells are stacked with tf.layers.stackedRNNCells() and work as single RNNCells:




import * as tf from "@tensorflow/tfjs"
 
// Creating RNNcells for stack
const cell1 = tf.layers.simpleRNNCell({units: 2});
const cell2 = tf.layers.simpleRNNCell({units: 4});
 
// Stack all the RNNCells
const cell = tf.layers.stackedRNNCells({ cells: [cell1, cell2]});
 
const input = tf.input({shape: [8]});
const output = cell.apply(input);
 
console.log(JSON.stringify(output.shape));

Output:

[null,8]

Example 2: In this example, we will combine a number of cells into a stacked RNN cell with the help of stackedRNNCells and used to create RNN. 




import * as tf from "@tensorflow/tfjs";
 
// Creating simple RNNCell for stacking together
const cell1 = tf.layers.simpleRNNCell({ units: 4 });
const cell2 = tf.layers.simpleRNNCell({ units: 8 });
const cell3 = tf.layers.simpleRNNCell({ units: 12 });
const cell4 = tf.layers.simpleRNNCell({ units: 16 });
 
const stacked_cell = tf.layers.stackedRNNCells({
    cells: [cell1, cell2, cell3, cell4],
    name: "Stacked_RNN",
    dtype: "int32",
});
 
const rnn = tf.layers.rnn({ cell: stacked_cell, returnSequences: true });
 
// Create input with 10 steps and 20 length vector at each step.
const input = tf.input({ shape: [8, 32] });
const output = rnn.apply(input);
 
console.log("Shape of output should be in : ", JSON.stringify(output.shape));

Output:

Shape of output should be in :  [null,8,16]

Reference: https://js.tensorflow.org/api/latest/#layers.stackedRNNCells


Article Tags :