Tensorflow.js tf.moments() Function
Last Updated :
10 Sep, 2021
The tf.moments() is used to calculate the mean and variance of tensor passed as an argument in the function. The mean and variance are calculated by aggregating the contents of the tensor across the axes passed in parameters.
Syntax:
tf.moments(tensor, axis, keepdims)
Parameters: This method accepts the following three parameters:
- tensor: It is used to denote a tensor (vector) whose mean and variance need to be computed.
- axis: A vector of integers representing axes along which mean and variance need to be computed.
- keepdims: Keep dimension is a boolean variable that indicates whether produced moments will have the same dimension as of input tensor.
Return Value: It returns Two Tensor objects i.e computed mean and variance.
Example 1: In this example, we will compute the true mean and variance of 1-D Tensor.
Javascript
const tensor = tf.tensor1d([1, 2, 3, 4, 5, 6, 7, 8, 9]);
const value = tf.moments(tensor,[0]);
console.log( "Mean: " ,value.mean, "\nVariance: " ,value.variance);
|
Output:
Mean: Tensor
5
Variance: Tensor
6.666666507720947
Example 2: In this example, we will compute the float value of the mean and variance of 2-D tensor.
Javascript
tensor = tf.tensor2d([[1,2,4],[3,7,4],[7,5,1]])
value = tf.moments(tensor,axes=[0])
console.log( "Mean: " ,value.mean, "\nVariance: " ,value.variance);
|
Output:
Mean: Tensor
[3.6666667, 4.666667, 3]
Variance: Tensor
[6.2222228, 4.2222223, 2]
Example 3: In the above example, the mean and variance are computed across axes[0] i.e. [(1+3+7)/3, (2+7+5)/3, (4+4+1)/3], In this example, we will set parameter axes to [1].
Javascript
tensor = tf.tensor2d([[3,2,4],[3,7,4],[7,5,1]]);
value = tf.moments(tensor,axes=[1])
console.log( "Mean: " ,value.mean, "\nVariance: " ,value.variance);
|
Output: Mean is calculated as [(3+2+4)/3 ,(3+7+4)/3 ,(7+5+1)/3]
Mean: Tensor
[3, 4.666667, 4.3333335]
Variance: Tensor
[0.6666667, 2.8888888, 6.2222228]
Example 4: In this example, we will compute the mean and variance of the complete vector by changing axes=[0,1].
Javascript
tensor = tf.tensor2d([[3,2,4],[3,7,4],[7,5,1]])
value = tf.moments(tensor,[0,1])
console.log( "Mean: " ,value.mean, "\nVariance: " ,value.variance);
|
Output:
Mean: Tensor
4
Variance: Tensor
3.777777910232544
Note: Calculating mean and variance is Normalization of Tensor. The tf.moments() will work fine in JavaScript but if we import the TensorFlow module in python we use tf.nn.moments() to perform the same operation.
Share your thoughts in the comments
Please Login to comment...