Open In App

Tensorflow.js tf.depthToSpace() function

Last Updated : 23 Jul, 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 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:

  • input: the given tensor
  • blocksize: the width of output tensor is depth *blockSize.
  • dataformat: specifies the layout of the given and resulting tensor. It has two options: “NHWC”: [ batch, height, width, channels ] and “NCHW”: [ batch, channels, height, width ]

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

Example 1: Using “NHWC” format

Javascript




// 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

Javascript




// 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



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

Similar Reads