Skip to content

Commit 745edaa

Browse files
battlecook권욱진battlecook
authored
add cosine similarity function to vector class (#35)
Co-authored-by: 권욱진 <[email protected]> Co-authored-by: battlecook <[email protected]>
1 parent c98a7b9 commit 745edaa

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

src/Vector.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,21 @@ public function magnitude()
8282
return $this->length();
8383
}
8484

85+
/**
86+
* @param self $other
87+
* @return float
88+
* @throws VectorException
89+
* @link https://en.wikipedia.org/wiki/Cosine_similarity
90+
*/
91+
public function cosineSimilarity(self $other): float
92+
{
93+
if ($other->getSize() !== $this->getSize()) {
94+
throw new VectorException('Vectors have to have same size');
95+
}
96+
97+
return $this->dotProduct($other) / ($this->l2Norm() * $other->l2Norm());
98+
}
99+
85100
/**
86101
* @param self $other
87102
* @return float

tests/VectorTest.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,14 @@ public function testDotProduct()
106106
$this->assertEquals((1 * -1) + (2 * 3) + (3 * 5) + (4 * 2), $vector1->dotProduct($vector2));
107107
}
108108

109+
public function testCosineSimilarity()
110+
{
111+
$vector1 = new Vector([1, 0, 1, 1]);
112+
$vector2 = new Vector([2, 0, 2, 2]);
113+
114+
$this->assertEquals(1.00, $vector1->cosineSimilarity($vector2));
115+
}
116+
109117
public function testOuterProduct()
110118
{
111119
$vector1 = new Vector([1, 2]);

0 commit comments

Comments
 (0)