Open In App

Tensorflow.js tf.sparseReshape() Function

Tensorflow.js is an open-source library that is developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment. The .sparseReshape() function possesses identical syntax like reshape() function on the rendered compressed tensor. Where the input indices are recalculated on the basis of the required new shape. 

Note:



Syntax:

tf.sparseReshape(inputIndices, inputShape, newShape)

Parameters: This method accepts the following parameter:



Return Value: It returns tf.Tensor object.

Example 1: In the following example, we have called sparse.sparseReshape() function with all its parameter and printed the output response without its indices and shape.




// Importing the tensorflow.js library
const tf = require("@tensorflow/tfjs")
  
// Calling sparse.sparseReshape() function
// with all its parameter
const res = tf.sparse.sparseReshape(
    [[1, 0, 1], [2, 0, 1], [1, 1, 2], [0, -1, 0], [-3, 1, 2]],
    [1, 2, 9], [-1, 9]);
  
// Printing output
console.log(res);

Output:

{
  "outputIndices": {
    "kept": false,
    "isDisposedInternal": false,
    "shape": [
      5,
      2
    ],
    "dtype": "float32",
    "size": 10,
    "strides": [
      2
    ],
    "dataId": {
      "id": 82
    },
    "id": 82,
    "rankType": "2",
    "scopeId": 36
  },
  "outputShape": {
    "kept": false,
    "isDisposedInternal": false,
    "shape": [
      2
    ],
    "dtype": "float32",
    "size": 2,
    "strides": [],
    "dataId": {
      "id": 83
    },
    "id": 83,
    "rankType": "1",
    "scopeId": 36
  }
}

Example 2: In the following example, we have called sparse.sparseReshape() function with all its parameter and printed the output response with its indices and shape.




// Importing the tensorflow.js library
const tf = require("@tensorflow/tfjs")
  
// Calling sparse.sparseReshape() function
// with all its parameter
const res = tf.sparse.sparseReshape(
    [[1.1, 0, 1.2], [2.1, 0.2, 1.3], [1.4, 2.3, 2.5], [null, -1, 0], [-3, 1, 2]],
    [1.0, 3, 3], [-1, 9]);
  
// Printing output indices
res['outputIndices'].print();
  
// Printing output shape
res['outputShape'].print();

Output:

Tensor
    [[1 , 2 ],
     [2 , 2 ],
     [2 , 3 ],
     [0 , -3],
     [-2, -4]]
Tensor
    [1, 9]

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


Article Tags :