Friday, November 14, 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
32399 POSTS0 COMMENTS
Milvus
95 POSTS0 COMMENTS
Nango Kala
6765 POSTS0 COMMENTS
Nicole Veronica
11916 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11984 POSTS0 COMMENTS
Shaida Kate Naidoo
6889 POSTS0 COMMENTS
Ted Musemwa
7141 POSTS0 COMMENTS
Thapelo Manthata
6837 POSTS0 COMMENTS
Umr Jansen
6839 POSTS0 COMMENTS