VOOZH about

URL: https://www.geeksforgeeks.org/javascript/tensorflow-js-tf-tensor-function/

⇱ Tensorflow.js tf.tensor() Function - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Tensorflow.js tf.tensor() Function

Last Updated : 26 Jul, 2021

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. 

 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.

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.

Output:

Tensor
 [['1', '2', '3'],
 ['4', '5', '6']]

Printed the tensor of String type values.

Comment