Saturday, August 30, 2025
HomeLanguagesJavascriptTensorflow.js tf.losses.cosineDistance() Function

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:

  • 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
 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32249 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6617 POSTS0 COMMENTS
Nicole Veronica
11792 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11838 POSTS0 COMMENTS
Shaida Kate Naidoo
6731 POSTS0 COMMENTS
Ted Musemwa
7013 POSTS0 COMMENTS
Thapelo Manthata
6689 POSTS0 COMMENTS
Umr Jansen
6701 POSTS0 COMMENTS