• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python 求向量的余弦值操作

python 搞代码 4年前 (2022-01-08) 25次浏览 已收录 0个评论
文章目录[隐藏]

这篇文章主要介绍了Python 求向量的余弦值操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

1、余弦相似度

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

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

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

 def cosVector(x,y): if(len(x)!=len(y)): print('error input,x and y is not in the same space') return; result1=0.0; result2=0.0; result3=0.0; for i in range(len(x)): result1+=x[i]*y[i]  #sum(X*Y) result2+=x[i]**2   #sum(X*X) result3+=y[i]**2   #sum(Y*Y) #print(result1) #print(result2) #print(result3) print("result is "+str(result1/((result2*result3)**0.5))) #结果显示 cosVector([2,1],[1,1])

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

 #求余弦函数 def cosVector(x,y): if(len(x)!=len(y)): print('error input,x and y is not in the same space') return; result1=0.0; result2=0.0; result3=0.0; for i in range(len(x)): result1+=x[i]*y[i]  #sum(X*Y) result2+=x[i]**2   #sum(X*X) result3+=y[i]**2   #sum(Y*Y) #print("result is "+str(result1/((result2*result3)**0.5))) #结果显示 return result1/((result2*result3)**0.5) #print("result is ",cosVector([2,1],[1,1])) #计算query_output(60,20)和db_output(60,20)的余弦值,用60*1的向量存储 cosResult= [[0]*1 for i in range(60)] for i in range(60): cosResult[i][0]=cosVector(query_output[i], db_output[i]) print(cosResult) -------------------------------------------------------------------------------------------- #计算query_output和db_output的余弦值,用60*1的向量存储 rows=query_output.shape[0] #行数 cols=query_output.shape[1] #列数 cosResult= [[0]*1 for i in range(rows)] for i in range(rows): cosResult[i][0]=cosVector(query_output[i], db_output[i]) #print(cosResult) #将结果存入文件中,并且一行一个数字 file=open('cosResult.txt','w') for i in cosResult: file.write(str(i).replace('[','').replace(']','')+'\n') #\r\n为换行符 file.close()

补充:pyth来源gaodai#ma#com搞*!代#%^码$网on实现余弦近似度

方法一:

 def cos(vector1,vector2): dot_product = 0.0 normA = 0.0 normB = 0.0 for a,b in zip(vector1,vector2): dot_product += a*b normA += a**2 normB += b**2 if normA == 0.0 or normB==0.0: return None else: return 0.5 + 0.5 * dot_product / ((normA*normB)**0.5) #归一化 <span style="font-family: Arial, Helvetica, sans-serif">从[-1,1]到[0,1]</span>

方法二:

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

以上就是Python 求向量的余弦值操作的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python 求向量的余弦值操作
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址