Open In App

Tensorflow.js tf.reshape() Function

Last Updated : 21 Jun, 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 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:

  • x: It is the input tensor that needs to be shaped.
  • shape: We need to pass array of numbers to define the output shape.

Return Value: It returns a tf.Tensor.

Example 1:

Javascript




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

Javascript




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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads