Skip to content

Commit

Permalink
add cosine similarity function to vector class (#35)
Browse files Browse the repository at this point in the history
Co-authored-by: 권욱진 <[email protected]>
Co-authored-by: battlecook <[email protected]>
  • Loading branch information
3 people authored Oct 21, 2020
1 parent c98a7b9 commit 745edaa
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/Vector.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,21 @@ public function magnitude()
return $this->length();
}

/**
* @param self $other
* @return float
* @throws VectorException
* @link https://en.wikipedia.org/wiki/Cosine_similarity
*/
public function cosineSimilarity(self $other): float
{
if ($other->getSize() !== $this->getSize()) {
throw new VectorException('Vectors have to have same size');
}

return $this->dotProduct($other) / ($this->l2Norm() * $other->l2Norm());
}

/**
* @param self $other
* @return float
Expand Down
8 changes: 8 additions & 0 deletions tests/VectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,14 @@ public function testDotProduct()
$this->assertEquals((1 * -1) + (2 * 3) + (3 * 5) + (4 * 2), $vector1->dotProduct($vector2));
}

public function testCosineSimilarity()
{
$vector1 = new Vector([1, 0, 1, 1]);
$vector2 = new Vector([2, 0, 2, 2]);

$this->assertEquals(1.00, $vector1->cosineSimilarity($vector2));
}

public function testOuterProduct()
{
$vector1 = new Vector([1, 2]);
Expand Down

0 comments on commit 745edaa

Please sign in to comment.