Open In App

Tensorflow.js tf.TensorBuffer Class

Last Updated : 08 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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.

This TensorBuffer class mutable object is similar to tf.Tensor which permits users to set values at the specified locations before converting to an immutable tf.Tensor. For creating a tensor buffer, tf.buffer() is used. 

This TensorBuffer class is having three inbuilt functions which are illustrated below: 

  • tf.TensorBuffer class .set() function
  • tf.TensorBuffer class .get() function
  • tf.TensorBuffer class .toTensor() function

The tf.TensorBuffer class .set() function is used to sets a given value in the buffer at a specified location.

 

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
buffer.toTensor().print();


Output:

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

The tf.TensorBuffer class .get() function is used to return the value in the specified buffer for the given location.

Example 2:

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); 
  
// Getting the values for the
// specified indices with the
// help of .get() function
console.log(buffer.get(0, 0));
console.log(buffer.get(1, 0));


Output: The tf.TensorBuffer class .toTensor() function is used to create an immutable Tensor object from the specified buffer and its values.

5
10 

Example 3:

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],

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads