Python 求向量的余弦值操作


Posted in Python onMarch 04, 2021

1、余弦相似度

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

Python 求向量的余弦值操作

余弦相似度的取值为[-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()

补充:python实现余弦近似度

方法一:

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 相关文章推荐
python自定义类并使用的方法
May 07 Python
VScode编写第一个Python程序HelloWorld步骤
Apr 06 Python
python安装scipy的步骤解析
Sep 28 Python
Django实现文件上传和下载功能
Oct 06 Python
pytorch方法测试——激活函数(ReLU)详解
Jan 15 Python
使用tensorflow实现矩阵分解方式
Feb 07 Python
在Django中预防CSRF攻击的操作
Mar 13 Python
Python logging模块写入中文出现乱码
May 21 Python
python代码实现将列表中重复元素之间的内容全部滤除
May 22 Python
Python基于yaml文件配置logging日志过程解析
Jun 23 Python
python db类用法说明
Jul 07 Python
pytorch 中forward 的用法与解释说明
Feb 26 Python
django使用多个数据库的方法实例
Mar 04 #Python
Python使用paramiko连接远程服务器执行Shell命令的实现
Mar 04 #Python
Python 调用C++封装的进一步探索交流
Mar 04 #Python
使用Python webdriver图书馆抢座自动预约的正确方法
Mar 04 #Python
Python与C/C++的相互调用案例
Mar 04 #Python
解决Python import .pyd 可能遇到路径的问题
Mar 04 #Python
关于PySnooper 永远不要使用print进行调试的问题
Mar 04 #Python
You might like
第十一节 重载 [11]
2006/10/09 PHP
社区(php&amp;&amp;mysql)五
2006/10/09 PHP
discuz authcode 经典php加密解密函数解析
2020/07/12 PHP
PHP格式化显示时间date()函数代码
2018/10/03 PHP
Laravel关联模型中过滤结果为空的结果集(has和with区别)
2018/10/18 PHP
HTML TO JavaScript 转换
2006/06/26 Javascript
jQuery拖动元素并对元素进行重新排序
2015/12/30 Javascript
关于JS中match() 和 exec() 返回值和属性的测试
2016/03/21 Javascript
D3.js实现散点图和气泡图的方法详解
2016/09/21 Javascript
jQuery Ajax请求后台数据并在前台接收
2016/12/10 Javascript
JS设置时间无效问题的解决办法
2017/02/18 Javascript
jQuery validate 验证radio实例
2017/03/01 Javascript
NodeJS 实现手机短信验证模块阿里大于功能
2017/06/19 NodeJs
解决Nuxt使用axios跨域问题
2020/07/06 Javascript
vue - props 声明数组和对象操作
2020/07/30 Javascript
vue+高德地图实现地图搜索及点击定位操作
2020/09/09 Javascript
微信小程序实现页面左右滑动
2020/11/16 Javascript
Python迭代用法实例教程
2014/09/08 Python
Python爬虫框架Scrapy实战之批量抓取招聘信息
2015/08/07 Python
python+django+sql学生信息管理后台开发
2018/01/11 Python
python脚本监控Tomcat服务器的方法
2018/07/06 Python
python调用百度REST API实现语音识别
2018/08/30 Python
在python中对变量判断是否为None的三种方法总结
2019/01/23 Python
详解重置Django migration的常见方式
2019/02/15 Python
Python基于class()实现面向对象原理详解
2020/03/26 Python
简单的命令查看安装的python版本号
2020/08/28 Python
用css3实现当鼠标移进去时当前亮其他变灰效果
2014/04/08 HTML / CSS
英国最大的体育&时尚零售公司:JD Sports
2017/12/13 全球购物
贝玲妃英国官网:Benefit英国
2018/02/03 全球购物
水上运动奥特莱斯:Wasterports Outlet
2018/08/08 全球购物
语文课外活动总结
2014/08/27 职场文书
高中课前三分钟演讲稿
2014/09/13 职场文书
十八大标语口号
2014/10/09 职场文书
幼儿教师师德师风自我评价
2015/03/05 职场文书
2016计算机专业毕业生自荐信
2016/01/28 职场文书
python实现简单的聊天小程序
2021/07/07 Python