Open In App

Tensorflow.js tf.depthToSpace() 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 also helps the developers to develop ML models in JavaScript language and can use ML directly in the browser or in Node.js.

The tf.depthToSpace() is an inbuilt function of tensorflow.js library, which is used to rearrange data in the input tensor, where values from the depth dimension are moved in spatial blocks to the height and width dimensions. It rearranges data from depth into blocks of spatial data.



Syntax:

tensor.depthToSpace(input, blocksize, dataformat)

Parameters:



Return value: It returns the rearranged tensor of the same data type.

Example 1: Using “NHWC” format




// Importing the tensorflow.Js library
import * as tf from "@tensorflow/tfjs"
 
// Create a new tensor
var input = tf.tensor4d([1, 3, 5, 7], [1, 1, 1, 4]);
 
// define block size
var blockSize = 2;
 
// define data format
var dataFormat = "NHWC";
 
// rearrange data
var val = tf.depthToSpace(input, blockSize, dataFormat);
 
// print the tensor
val.print();

 Output:

Tensor
    [[[[1],
       [3]],

      [[5],
       [7]]]]

Example 2: using “NCHW” format




// Importing the tensorflow.Js library
import * as tf from "@tensorflow/tfjs"
 
// Create a new tensor
var input = tf.tensor4d([1, 3, 5, 7], [1, 4, 1, 1]);
 
// define block size
var blockSize = 2;
 
// define data format
var dataFormat = "NCHW";
 
// rearrange data
var tr = tf.depthToSpace(input, blockSize, dataFormat);
 
// print the tensor
tr.print();

 
Output: 

Tensor
    [[[[1, 3],
       [5, 7]]]]

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


Article Tags :