Open In App

Tensorflow.js tf.sparseToDense() Function

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.sparseToDense() function is used to convert a specified sparse representation into a dense Tensor. If the given indices get repeated, the final value is summed over all values for that indices.



Syntax:

tf.sparseToDense(sparseIndices, sparseValues, 
            outputShape, defaultValue)

Parameters: This function accepts four parameters which are illustrated below:



Example 1:




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
 
// Initializing indices and values
const indices = tf.tensor1d([4, 3, 2, 1, 0], 'int32');
const values = tf.tensor1d([1111, 111, 11, 1, 0.1], 'float32');
 
// Specifying shape for the output dense
const shape = [7];
 
// Getting the Dense representation for the above
// sparse representation
tf.sparseToDense(indices, values, shape).print();

 

 

Output:

 

 Tensor
   [0.1, 1, 11, 111, 1111, 0, 0]

 

Example 2:

 




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
 
// Initializing indices and values
const indices = tf.tensor1d([1, 2, 3], 'int32');
const values = tf.tensor1d([10, 20, 30], 'float32');
 
// Getting the Dense representation for the above
// sparse representation along with shape of [6]
// and default value of 55
tf.sparseToDense(indices, values, [6], 55).print();

 

 

Output:

 

Tensor
   [55, 10, 20, 30, 55, 55]

 

Reference: https://js.tensorflow.org/api/latest/#sparseToDense

 


Article Tags :