File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change 3333var similarity = Object . create ( null ) ;
3434similarity . bow = Object . create ( null ) ;
3535similarity . set = Object . create ( null ) ;
36+ similarity . vector = Object . create ( null ) ;
3637
3738/**
3839 *
@@ -177,5 +178,29 @@ similarity.set.oo = function ( setA, setB ) {
177178
178179} ; // similarity.set.oo()
179180
181+ /**
182+ *
183+ * Computes the cosine similarity between the input vectors
184+ * `vectorA` and `vectorB` and returns a value between 0 and 1.
185+ * Note, in winkNLP all vectors contain the `l2Norm` as the last
186+ * element of the array.
187+ *
188+ * @param {object } vectorA the first vector
189+ * @param {object } vectorB the second vector.
190+ * @return {number } cosine similarity between `vectorA` and `vectorB`.
191+ */
192+ similarity . vector . cosine = function ( vectorA , vectorB ) {
193+ let sumOfProducts = 0 ;
194+ // Recall, the last element is always the `l2Norm`.
195+ const length = vectorA . length - 1 ;
196+
197+ for ( let i = 0 ; i < length ; i += 1 ) {
198+ sumOfProducts += vectorA [ i ] * vectorB [ i ] ;
199+ }
200+
201+ // Use `l2Norm` directly from each vector.
202+ return + ( sumOfProducts / ( vectorA [ length ] * vectorB [ length ] ) ) . toFixed ( 4 ) ;
203+ } ; // similarity.vector.cosine()
204+
180205// Export similarity
181206module . exports = similarity ;
You can’t perform that action at this time.
0 commit comments