Introduction: Tensorflow.js is an open-source library that is developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment. Tensorflow.js tf.bincount() function generate the tensor of provided size with the same data type. The values of the tensor would be the sum of numbers at an index of provided weight tensor which corresponds to the index of the index number in the input tensor. Â
Syntax:Â
tf.bincount( x ,weights ,size )
Parameters:Â
- x: The stated variable is the input tensor. It should be of 1d tensor.
- weights: The stated variable is a tensor of the same size as x. It is the corresponds values to the value in the x tensor.
- size: The state value is the size of the output tensor.
Returns: tf.tensor1D
Basic Example of tf.bincount() function:
Example 1: In this example, we create a tensor and count the occurrence of the number between the size and print it.Â
Javascript
// Importing tensorflow.js libraryimport * as tf from "@tensorflow/tfjs"Â Â // Initializing the inputconst geek_input = tf.tensor([1, 2, 9, 6, 5, 4, 7, Â Â Â Â 4, 7, 4, 3, 2, 4, 2, 5, 1], [1, 16], 'int32');Â
// Printing Input tensorconsole.log('Input tensor: ',geek_input)Â
// Weight and size for the bincountconst geek_Weight = [];const geek_size = 5;Â
// Applying bincount to input tensorconst r = tf.bincount(geek_input, geek_Weight,geek_size)Â
// Printing resultconsole.log("Number of Index Number in tensor: ",r)Â
// Printing Occurrence of index in tensor const r1 = r.arraySync();r1.map((e,i) => {console.log(`Index ${i} occurs`, e ,"times")}) |
Output:Â Â
Input tensor: Tensor
[[1, 2, 9, 6, 5, 4, 7, 4, 7, 4, 3, 2, 4, 2, 5, 1],]
Number of Index Number in tensor:
Tensor
[0, 2, 3, 1, 4]
Index 0 occurs 0 times
Index 1 occurs 2 times
Index 2 occurs 3 times
Index 3 occurs 1 times
Index 4 occurs 4 times
Example 2: In this example, we create an input tensor and weight tensor and pass it to the bincount function and see how bincount calculates the value for the output tensor. Â
Javascript
// Importing tensorflow.js libraryimport * as tf from "@tensorflow/tfjs"Â Â // Initializing the inputconst geek_input = tf.tensor([1, 2, 9, 6, 5, Â Â Â Â 4, 7, 4, 7, 4, 3], [1, 11], 'int32');Â
// Printing Input tensorconsole.log('Input tensor: ',geek_input)Â
// Weight and size for the bincountconst geek_Weight = tf.tensor(    [0, 2, 5, 8, 9, 3, 5, 5, 3, 8, 2]);Â
const geek_size = 8;Â
// Applying bincount to input tensorconst r = tf.bincount(geek_input,geek_Weight,geek_size)Â
// Printing resultconsole.log("Output tensor: ",r) |
Output:Â
Input tensor: Tensor
[[1, 2, 9, 6, 5, 4, 7, 4, 7, 4, 3],]
Output tensor: Tensor
[0, 0, 2, 2, 16, 9, 8, 8]
Reference: https://js.tensorflow.org/api/latest/#bincount
Â
