Open In App

Tensorflow.js tf.cumsum() Function

TensorFlow.js is a library for machine learning in JavaScript. It helps developers to develop ML models in JavaScript, and use ML directly in the browser or in Node.js.

The tf.cumsum() function is used to compute the cumulative sum of a tf.Tensor along the specified axis. The meaning of exclusive cumulative sum for a tensor is that each tensor entry does not include its own value, but only the values previous to it along the specified axis in the exclusive cumulative sum.



Syntax:

tf.cumsum(x, axis, exclusive, reverse)

Parameters: This method has four parameters as mentioned above and described below:



Return Value: It returns a tf.Tensor denotes the cumulative sum of the given tensor.

The below examples demonstrate the tf.cumsum() method.

Example 1:




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
 
// Creating and initializing a new variable
const x = tf.tensor([1, 2, 3, 4]);
 
// Finding the cumulative sum
const a=x.cumsum();
 
// Printing the tensor
a.print();

 
Output: 

Tensor
   [1, 3, 6, 10]

 

Example 2:

 




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
 
// Creating and initializing a new variable
const x = tf.tensor([1, 2, 3, 4]);
 
// Finding the cumulative sum
const a=x.cumsum(0,true,true);
 
// Printing the tensor
a.print();

 
Output: 

Tensor
   [9, 7, 4, 0]

 

Example 3:

 




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
 
// Creating and initializing a new variable
const x = tf.tensor([[1, 2],[3, 4]]);
 
// Finding the cumulative sum
const a=x.cumsum();
 
// Printing the tensor
a.print();

 
 Output: 

Tensor
   [[1, 2],
    [4, 6]]

Example 4:




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
 
// Creating and initializing a new variable
const x = tf.tensor([[1, 2],[3, 4]]);
 
// Finding the cumulative sum
const a=x.cumsum(1);
 
// Printing the tensor
a.print();

 
 

Output:

Tensor
   [[1, 3],
    [3, 7]]

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

 


Article Tags :