Skip to content
Related Articles

Related Articles

Tensorflow.js tf.cumsum() Function

Improve Article
Save Article
Like Article
  • Last Updated : 20 Jul, 2021

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:

  • x: The input tensor which has to be summed. It is of type tf.Tensor, TypedArray, or Array.
  • axis: The axis along which we have to sum. It is an optional parameter. The default value is 0.
  • exclusive: It decides whether to find an exclusive cumulative sum or not. It is a boolean value and defaults to false. It is an optional parameter.
  • reverse: It decides whether to sum in the opposite direction. It is a boolean value and defaults to false. It is also an optional parameter.

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:

Javascript




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

 

Javascript




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

 

Javascript




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

Javascript




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

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!