Saturday, September 6, 2025
HomeLanguagesJavascriptTensorflow.js tf.stack() Function

Tensorflow.js tf.stack() 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. 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

RELATED ARTICLES

Most Popular

Dominic
32269 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6639 POSTS0 COMMENTS
Nicole Veronica
11803 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11868 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6704 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS