Open In App

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

The tf.reshape() function is used to reshape a given tensor with the specified shape.



Syntax:

tf.reshape(x, shape)

Parameters: This function has the following parameters:



Return Value: It returns a tf.Tensor.

Example 1:




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
const x = tf.tensor1d([10, 15, 16, 24]);
  
// Print the tensor
x.reshape([2, 2]).print();

Output:

Tensor
    [[10, 15],
     [16, 24]]

Example 2:




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Using 2d
const x = tf.tensor2d(
  [1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 3]
);
x.reshape([3, 3]).print();
  
// Using 3d
const y = tf.tensor3d(
  [[[1], [2]], [[3], [4]]]
);
y.reshape([2, 2]).print();
  
// Using 4d
const z = tf.tensor4d(
  [11, 12, 13, 14], [1, 2, 2, 1]
);
z.reshape([2, 2]).print();

Output:

Tensor
    [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]
Tensor
    [[1, 2],
     [3, 4]]
Tensor
    [[11, 12],
     [13, 14]]

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

Article Tags :