Open In App

Tensorflow.js tf.losses.cosineDistance() 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.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:



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

Example 1:




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




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


Article Tags :