Tensorflow.js tf.TensorBuffer Class
Last Updated :
08 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.
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
import * as tf from "@tensorflow/tfjs"
const buffer = tf.buffer([2, 2]);
buffer.set(5, 0, 0);
buffer.set(10, 1, 0);
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
import * as tf from "@tensorflow/tfjs"
const buffer = tf.buffer([2, 2]);
buffer.set(5, 0, 0);
buffer.set(10, 1, 0);
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
import * as tf from "@tensorflow/tfjs"
const buffer = tf.buffer([2, 2]);
buffer.set(5, 0, 0);
buffer.set(10, 1, 0);
buffer.toTensor().print();
|
Output:
Tensor
[[5 , 0],
Reference: https://js.tensorflow.org/api/latest/#class:TensorBuffer
Share your thoughts in the comments
Please Login to comment...