File tree Expand file tree Collapse file tree 2 files changed +23
-0
lines changed Expand file tree Collapse file tree 2 files changed +23
-0
lines changed Original file line number Diff line number Diff 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
Original file line number Diff line number Diff 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 ]);
You can’t perform that action at this time.
0 commit comments