Open In App

Tensorflow.js tf.stack() Function

Last Updated : 10 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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. It helps developers to develop ML models in JavaScript, and use ML directly in the browser or in Node.js.

The tf.stack() function is used to create a stack of tf,tensors into an r+1 rank tf.tensor.

Syntax:

tf.stack(tensors, axis)

Parameters: This function accepts two parameters as mentioned above and discussed below.

  • tensors: list of tensor objects to be used, with the same shape and dtype.
  • axis: It is an axis of the stack along.

Return Value: It returns tf.Tensor.

Example 1:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
// Making a tensor a
const a = tf.tensor1d([99, 999, 999]);
  
// Making a tensor b
const b = tf.tensor1d([322, 411, 888]);
  
// Making a tensor c
const c = tf.tensor1d([523, 622, 666]);
  
// Printing the stack
tf.stack([a, b, c]).print();


Output:

Tensor
    [[99 , 999, 999],
     [322, 411, 888],
     [523, 622, 666]]

Example 2: In this example, making the stack with axis as the 2nd parameter.

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
// Making a tensor a
const a = tf.tensor1d([99, 999, 999]);
  
// Making a tensor b
const b = tf.tensor1d([322, 411, 888]);
  
// Making a tensor c
const c = tf.tensor1d([523, 622, 666]);
  
// Printing the stack
tf.stack([a, b, c], 1).print();


Output:

Tensor
    [[99 , 322, 523],
     [999, 411, 622],
     [999, 888, 666]]

Reference: https://js.tensorflow.org/api/latest/#stack


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads