Open In App

Tensorflow.js tf.tensor() 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 .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: 



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. 




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




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




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


Article Tags :