Thursday, October 16, 2025
HomeLanguagesJavascriptTensorflow.js tf.sparseToDense() Function

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:

  • sparseIndices: It is a 0-D, 1-D, or 2-D Tensor of data type int32. Here sparseValues[i] get placed at sparseIndices[i], where i is the indices values.
  • sparseValues: It is a 0-D or 1-D Tensor of values which corresponds to each row of sparseIndices.
  • outputShape: It is the shape of the converted dense output tensor.
  • defaultValue: It is the value to set for indices not specified in sparseIndices. Its default value is zero. It is an optional parameter.

Example 1:

Javascript




// 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:

 

Javascript




// 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

 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11953 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS