Tensorflow.js tf.tensor2d() 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. The .tensor2d() function is used to create a new 2-dimensional tensor with the parameter namely value, shape, and datatype.
Syntax:
tf.tensor2d (value, shape, datatype)
Parameters:
- value: The value of the tensor which can be nested array of numbers, or a flat array, or a TypedArray.
- shape: It takes the shape of the tensor. The tensor will infer its shape from the value if it is not provided. It is an optional parameter.
- datatype: It can be a ‘float32’ or ‘int32’ or ‘bool’ or ‘complex64’ or ‘string’ value. It is an optional parameter.
Return Value: It returns the tensor of the same data type. The returned tensor will always be 2-dimensional.
Note: The 2d tensor functionality can also be achieved using tf.tensor() function, but using tf.tensor2d() makes the code easily understandable and readable.
Example 1: In this example, we are creating a 2D tensor and printing it. For creating a 2D tensor we are using the .tensor2d() function, and we use .print() function to print the tensor. Here, we will pass the 2D array (i.e. nested array) to the value parameter.
Javascript
import * as tf from "@tensorflow/tfjs" ;
let example1 = tf.tensor2d([ [ 1, 2, 3 ], [ 4, 5, 6 ] ]);
example1.print()
|
Output:
Tensor
[[1, 2, 3],
[4, 5, 6]]
Example 2: In this example, we are creating the tensor where we are passing the flat array and specifying the shape parameter of the tensor. We will see the usage of shape parameter here.
Javascript
import * as tf from "@tensorflow/tfjs" ;
const value = [1, 2, 3, 4, 5, 6, 7, 8];
const shape = [2, 4];
let example2 = tf.tensor2d(value, shape);
example2.print();
|
Output:
Tensor
[[1, 2, 3, 4],
[5, 6, 7, 8]]
In the above example, we have created a tensor of 2 x 4 dimension.
Example 3: In this example, we will create a tensor by specifying the value, shape, and datatype. We will create the tensor where all the values are of string datatype.
Javascript
import * as tf from "@tensorflow/tfjs" ;
const value = [ "C" , "C++" , "Java" , "Python" ,
"PHP" , "JS" , "SQL" , "React" ];
const shape = [2, 4];
const datatype = "string" ;
let example3 = tf.tensor2d(value, shape, datatype);
example3.print();
|
Output:
Tensor
[['C' , 'C++', 'Java', 'Python'],
['PHP', 'JS' , 'SQL' , 'React' ]]
In the above example, the printed values of the tensor are of string datatype.
Reference: https://js.tensorflow.org/api/latest/#tensor2d
Last Updated :
28 Apr, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...