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 library import * as tf from "@tensorflow/tfjs" // Initializing the input const 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 tensor console.log( 'Input tensor: ' ,geek_input) // Weight and size for the bincount const geek_Weight = []; const geek_size = 5; // Applying bincount to input tensor const r = tf.bincount(geek_input, geek_Weight,geek_size) // Printing result console.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 library import * as tf from "@tensorflow/tfjs" // Initializing the input const geek_input = tf.tensor([1, 2, 9, 6, 5, 4, 7, 4, 7, 4, 3], [1, 11], 'int32' ); // Printing Input tensor console.log( 'Input tensor: ' ,geek_input) // Weight and size for the bincount const geek_Weight = tf.tensor( [0, 2, 5, 8, 9, 3, 5, 5, 3, 8, 2]); const geek_size = 8; // Applying bincount to input tensor const r = tf.bincount(geek_input,geek_Weight,geek_size) // Printing result console.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