Saturday, January 31, 2026
HomeLanguagesJavascriptTensorflow.js tf.TensorBuffer Class .toTensor() Method

Tensorflow.js tf.TensorBuffer Class .toTensor() Method

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 tf.TensorBuffer class .toTensor() function is used to create an immutable Tensor object from the specified buffer and its values.

Syntax:

toTensor ()

Parameters: This function does not accept any parameters.

Return Value: It returns the created immutable Tensor object.

Example 1:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Creating a buffer of 2*2 dimensions
const buffer = tf.buffer([2, 2]); 
  
// Setting values at particular indices. 
buffer.set(5, 0, 0); 
buffer.set(10, 1, 0); 
  
// Converting the above buffer back
// to a tensor value to print with 
// the help of .toTensor() function
buffer.toTensor().print();


Output:

Tensor
  [[5 , 0],
   [10, 0]]

Example 2:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Creating a buffer of 3*3 dimensions
const buffer = tf.buffer([3, 3]); 
  
// Setting values at particular indices. 
buffer.set(5, 0, 0); 
buffer.set(10, 0, 1); 
buffer.set(15, 1, 0); 
buffer.set(20, 1, 1); 
buffer.set(25, 2, 0); 
buffer.set(30, 2, 1); 
buffer.set(35, 2, 2); 
  
// Converting the above buffer back 
// to a tensor value to print with
// the help of .toTensor() function
buffer.toTensor().print()


Output:

Tensor
  [[5 , 10, 0 ],
   [15, 20, 0 ],
   [25, 30, 35]]

Reference: https://js.tensorflow.org/api/latest/#tf.TensorBuffer.toTensor

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32478 POSTS0 COMMENTS
Milvus
122 POSTS0 COMMENTS
Nango Kala
6849 POSTS0 COMMENTS
Nicole Veronica
11978 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12066 POSTS0 COMMENTS
Shaida Kate Naidoo
6987 POSTS0 COMMENTS
Ted Musemwa
7222 POSTS0 COMMENTS
Thapelo Manthata
6934 POSTS0 COMMENTS
Umr Jansen
6917 POSTS0 COMMENTS