Every line of 'cosine similarity calculator' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.
10 def cosine_similarity(x, y): 11 numerator = sum(a * b for a, b in zip(x, y)) 12 denominator = square_rooted(x) * square_rooted(y) 13 try: 14 return numerator / float(denominator) 15 except ZeroDivisionError: 16 return 0.0
47 def computeCosineDistance(vector1, vector2): 48 return 1 - spatial.distance.cosine(vector1, vector2)
81 def test_cosine_identical(self): 82 cosine = CosineTextSimilarity(self.ilist) 83 cosine_sim = cosine(self.ilist[0], self.ilist[0]) 84 self.assertAlmostEqual(cosine_sim, 1, places=5)
307 def CosineSimilarity(v1, v2): 308 """ Implements the Cosine similarity metric. 309 This is the recommended metric in the LaSSI paper 310 311 **Arguments**: 312 313 - two vectors (sequences of bit ids) 314 315 **Returns**: a float. 316 317 **Notes** 318 319 - the vectors must be sorted 320 321 >>> print('%.3f'%CosineSimilarity( (1,2,3,4,10), (2,4,6) )) 322 0.516 323 >>> print('%.3f'%CosineSimilarity( (1,2,2,3,4), (2,2,4,5,6) )) 324 0.714 325 >>> print('%.3f'%CosineSimilarity( (1,2,2,3,4), (1,2,2,3,4) )) 326 1.000 327 >>> print('%.3f'%CosineSimilarity( (1,2,2,3,4), (5,6,7) )) 328 0.000 329 >>> print('%.3f'%CosineSimilarity( (1,2,2,3,4), () )) 330 0.000 331 332 """ 333 d1 = Dot(v1, v1) 334 d2 = Dot(v2, v2) 335 denom = math.sqrt(d1 * d2) 336 if not denom: 337 res = 0.0 338 else: 339 numer = Dot(v1, v2) 340 res = numer / denom 341 return res
158 def cosine_distance(s1, s2, k): 159 """Compute the cosine difference of the strings as kmer vectors 160 """ 161 vec1, vec2 = to_kmer_vector(s1, s2, k) 162 163 intersection = set(vec1.keys()) & set(vec2.keys()) 164 numerator = sum([vec1[x] * vec2[x] for x in intersection]) 165 166 sum1 = sum([vec1[x] ** 2 for x in vec1.keys()]) 167 sum2 = sum([vec2[x] ** 2 for x in vec2.keys()]) 168 denominator = math.sqrt(sum1) * math.sqrt(sum2) 169 if not denominator: 170 return 0.0 171 else: 172 return float(numerator) / denominator
22 def cos_simi(vector1,vector2): 23 dot_product = 0.0 24 normA = 0.0 25 normB = 0.0 26 27 for a,b in zip(vector1,vector2): 28 dot_product += a*b 29 normA += a**2 30 normB += b**2 31 32 33 if normA == 0.0 or normB==0.0: 34 return None 35 else: 36 return dot_product / ((normA*normB)**0.5)
48 def cosSim(v1, v2): 49 N = dot(v1, v2) 50 D = dist((0,0), v1)*dist((0,0), v2) 51 52 if D <= 0.01: D = 0.01 53 54 return N/D
478 def cosine_similarity(v1, v2): 479 """Cosine similarity [-1, 1]. 480 481 Parameters 482 ---------- 483 v1, v2 : Tensor 484 Tensor with the same shape [batch_size, n_feature]. 485 486 References 487 ---------- 488 - `Wiki `__. 489 490 """ 491 492 return tf.reduce_sum(tf.multiply(v1, v2), 1) / \ 493 (tf.sqrt(tf.reduce_sum(tf.multiply(v1, v1), 1)) * 494 tf.sqrt(tf.reduce_sum(tf.multiply(v2, v2), 1)))