Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Tensorflow.js tf.losses.cosineDistance() Function

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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.losses.cosineDistance() function is used to Compute the cosine distance loss between two tensors.

Syntax:

tf.losses.cosineDistance(labels, predictions, 
        axis, weights?, reduction?) 

Parameters: This function accepts five parameters in which the last two are optional, which are illustrated below:

  • labels: The ground truth output tensor. The dimensions will be the same as predictions.
  • predictions: The predicted outputs.
  • axis: The cosine distance is computed along this dimension.
  • weights: It is a Tensor having rank 0, or the same rank as labels, and it must be broadcastable to labels that mean all the dimensions must be either 1, or the same as the corresponding losses dimension. This parameter is optional.
  • reduction: The type of reduction to apply to loss. This is also an optional parameter.

Return Value: It returns a Tensor which is a cosine distance loss between two tensors.

Example 1:

Javascript




// Importing the tensorflow.Js library
import * as tf from "@tensorflow/tfjs"
 
// Creating labels tensor
const a = tf.tensor2d([[1, 4, 5], [5, 5, 7]]);
 
// Creating predictions tensor
const b = tf.tensor2d([[3, 2, 5], [3, 2, 7]])
 
// Computing cosine distance
cosine = tf.losses.cosineDistance(a, b)
cosine.print();

Output:

Tensor
    -109

Example 2: In this example, we will pass one extra parameter that is weight. This is an optional parameter.

Javascript




// Importing the tensorflow.Js library
import * as tf from "@tensorflow/tfjs"
 
// Creating labels tensor
const a = tf.tensor2d([
    [1, 4, 5, 5, 5, 7],
    [4, 7, 6, 8, 9, 4]
]);
 
// Creating predictions tensor
const b = tf.tensor2d([
    [3, 2, 5, 3, 2, 7],
    [3, 5, 7, 2, 4, 5]
]);
 
// Computing cosine distance
cosine = tf.losses.cosineDistance(a, b , 1)
cosine.print();

Output:

Tensor
   -134.5

Reference: https://js.tensorflow.org/api/latest/#losses.cosineDistance
 


My Personal Notes arrow_drop_up
Last Updated : 22 Jul, 2021
Like Article
Save Article
Similar Reads
Related Tutorials