LLPhant icon indicating copy to clipboard operation
LLPhant copied to clipboard

Add similarity cosinus

Open ClicShopping opened this issue 9 months ago • 0 comments

Hello, I will be great if with can choose between euclidian and cosinus similarity in LLPhant\Embeddings\VectorStores\DistancesL2Utils.

This 2 approaches have advantage and disavantage in function what we want to do.

Example :

 public function cosineSimilarity($vector1, $vector2): float|int
  {
    // Calculate the dot product of the two vectors
    $dotProduct = array_sum(array_map(function ($a, $b) {
      return $a * $b;
    }, $vector1, $vector2));

    // Calculate the magnitudes of each vector
    $magnitude1 = sqrt(array_sum(array_map(function ($a) {
      return $a * $a;
    }, $vector1)));

    $magnitude2 = sqrt(array_sum(array_map(function ($a) {
      return $a * $a;
    }, $vector2)));

    // Avoid division by zero
    if ($magnitude1 * $magnitude2 == 0) {
      return 0;
    }

    // Calculate the cosine similarity
    $cosineSimilarity = $dotProduct / ($magnitude1 * $magnitude2);

    return $cosineSimilarity;
  }

ClicShopping avatar May 09 '24 15:05 ClicShopping