如何操作Python求向量的余弦值

  介绍

本篇内容主要讲解”如何操作Python求向量的余弦值”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习”如何操作Python求向量的余弦值”吧!

1,余弦相似度

余弦相似度衡量的是2个向量间的夹角大小,通过夹角的余弦值表示结果,因此2个向量的余弦相似度为:

如何操作Python求向量的余弦值

余弦相似度的取值为(1,- 1),值越大表示越相似。

向量夹角的余弦公式很简单,不在此赘述,直接上代码:

def  cosVector (x, y):   如果才能(len (x) !=len (y)):   ,,,print (& # 39; error 输入,x 以及y  is  not 拷贝,same 空间# 39;)   ,,,返回;   result1=0.0编写此表达式才能;   result2才能=0.0;   result3才能=0.0;   for 才能小姐:拷贝范围(len (x)):   ,,,result1 +编写此表达式y=x[我]*[我],,#总和(x * y)   ,,,result2 +=x[我]* * 2,,,#总和(x * x)   ,,,result3 +=y[我]* * 2,,,# (* y)和   #才能打印(result1)编写此表达式   #才能打印(result2)   #才能打印(result3)   打印才能(“result  is “+ str (result1/编写此表达式(0.5 (result2 * result3) * *))), #结果显示   cosVector ([2,1], [1])

一个计算二维数组余弦值的例子:

#求余弦函数   def  cosVector (x, y):   如果才能(len (x) !=len (y)):   ,,,print (& # 39; error 输入,x 以及y  is  not 拷贝,same 空间# 39;)   ,,,返回;   result1=0.0编写此表达式才能;   result2才能=0.0;   result3才能=0.0;   for 才能小姐:拷贝范围(len (x)):   ,,,result1 +编写此表达式y=x[我]*[我],,#总和(x * y)   ,,,result2 +=x[我]* * 2,,,#总和(x * x)   ,,,result3 +=y[我]* * 2,,,# (* y)和   #才能打印(“result  is “+ str (result1/编写此表达式(0.5 (result2 * result3) * *))), #结果显示   return 才能;result1/编写此表达式((result2 * result3) * * 0.5)   #打印(“result  is “, cosVector ((2, 1) [1]))   ,   20 #计算query_output(60)和db_output(60岁,20)的余弦值,用60 * 1的向量存储,   cosResult=, [[0] * 1, for 小姐:拷贝范围(60)],   ,   for 小姐:拷贝范围(60):   cosResult才能[我][0]=cosVector (query_output[我],db_output[我])   ,   打印(cosResult)   --------------------------------------------------------------------------------------------   #计算query_output和db_output的余弦值,用60 * 1的向量存储   行=query_output.shape[0], #行数   关口=query_output.shape[1], #列数   cosResult=, [[0] * 1, for 小姐:拷贝范围(行)],   ,   for 小姐:拷贝范围(行):   cosResult才能[我][0]=cosVector (query_output[我],db_output[我])   ,   #打印(cosResult)   #将结果存入文件中,并且一行一个数字   文件=打开(& # 39;cosResult.txt& # 39;, & # 39; w # 39;)   for 小姐:cosResult拷贝:   ,file.write (str (i) .replace (& # 39; [& # 39; & # 39; & # 39;) .replace (& # 39;] & # 39; & # 39; & # 39;) + & # 39; \ n # 39;), # \ r \ n为换行符,   file.close ()

<强>补充:python实现余弦近似度

方法一:

def 因为(vector1 vector2):,   dot_product 才能;0.0=,,   normA 才能;0.0=,,   normB 才能;0.0=,,   for 才能;b  zip (vector1 vector2):拷贝,   ,,,dot_product  +=, * b    ,,,normA  +=, * * 2,   ,,,normB  +=, b * * 2,   if 才能;normA ==, 0.0,趁机normB==0.0:,   ,,,return  None    ,,:   ,,,return  0.5, +, 0.5, *, dot_product /,((诺玛* normB) * * 0.5), #归一化,& lt; span 在从[1]到[0,1]& lt;/span>

方法二:

num =,浮子(* A.T  B), #若为行向量则,A  * B.T   时间=denom  linalg.norm (A), *, linalg.norm (B)   时间/时间=cos  num  denom  #余弦值   sim  0.5=,, +, 0.5, *, cos  #归一化,,从[1]到[0,1]

到此,相信大家对“如何操作Python求向量的余弦值”有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

如何操作Python求向量的余弦值