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 .tensor() function is used to create a new tensor with the help of value, shape, and data type.
Syntax :
tf.tensor( value, shape, dataType)
Parameters:
- Value: The value of the tensor which can be a simple or nested Array or TypedArray of numbers. If the array elements are Strings then they will encode as UTF-8 and kept as Uint8Array[ ].
- Shape [optional]: It is an optional parameter. It takes the shape of the tensor. If it is not provided, the tensor will infer its shape from the value.
- dataType [optional]: It is also optional parameter. It can be a ‘float32′ or ‘int32′ or ‘bool’ or ‘complex64′ or ‘string’.
Return Value: It returns the tensor of the same data type.
Example 1: In this example, we are creating a tensor and printing it. For creating a tensor we are using the .tensor() method and to print the tensor we are using the .print() method.
Javascript
// Importing the tensorflow.js library import * as tf from "@tensorflow/tfjs" // Creating the tensor var val = tf.tensor([1, 2, 3, 4, 5, 6, 7]); // Printing the tensor val.print() |
Output:
Tensor [1, 2, 3, 4, 5, 6, 7]
Example 2: In this example, we are creating the tensor where we did not mention the shape parameter of the tensor, let’s see the shape parameter here.
Javascript
// Importing the tensorflow library import * as tf from "@tensorflow/tfjs" // Defining the value of the tensor var value = [1, 2, 3, 4, 5, 6] // Specify the shape of the tensor var shape = [2, 3] // Creating the tensor var val = tf.tensor(value, shape) // Printing the tensor val.print() |
Output:
Tensor [[1, 2, 3], [4, 5, 6]]
The above example was creating the tensor of 2 × 3 dimensions.
Example 3: In this example, we are creating a tensor with value, shape, and dataType. We are creating the tensor of String type values.
Javascript
// Importing the tensorflow.Js library import * as tf from "@tensorflow/tfjs" // Creating a value variable which // stores the value var value = [ '1' , '2' , '3' , '4' , '5' , '6' ] // Creating a shape variable // which stores the shape var shape = [2, 3] // Creating a d_Type variable // which stores the data-type var d_Type = 'string' // Creating the tensor var val = tf.tensor(value, shape, d_Type) // Printing the tensor val.print() |
Output:
Tensor [['1', '2', '3'], ['4', '5', '6']]
Printed the tensor of String type values.