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 + openpyxl处理excel2007文档思路以及心得
Jul 14 Python
python实现的希尔排序算法实例
Jul 01 Python
python使用标准库根据进程名如何获取进程的pid详解
Oct 31 Python
python 设置文件编码格式的实现方法
Dec 21 Python
Python实现七彩蟒蛇绘制实例代码
Jan 16 Python
Python3使用Matplotlib 绘制精美的数学函数图形
Apr 11 Python
Python OpenCV实现视频分帧
Jun 01 Python
Python中面向对象你应该知道的一下知识
Jul 10 Python
PyCharm专业最新版2019.1安装步骤(含激活码)
Oct 09 Python
解决jupyter notebook打不开无反应 浏览器未启动的问题
Apr 10 Python
python用分数表示矩阵的方法实例
Jan 11 Python
python使用XPath解析数据爬取起点小说网数据
Apr 22 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
国王的咖啡这么大来头,名字的由来是什么
2021/03/03 咖啡文化
php访问查询mysql数据的三种方法
2006/10/09 PHP
destoon官方标签大全
2014/06/20 PHP
php+ajax 实现输入读取数据库显示匹配信息
2015/10/08 PHP
php7 安装yar 生成docker镜像
2017/05/09 PHP
jQuery ui 利用 datepicker插件实现开始日期(minDate)和结束日期(maxDate)
2014/05/22 Javascript
Js实现手机发送验证码时按钮延迟操作
2014/06/20 Javascript
JavaScript中的cacheStorage使用详解
2015/07/29 Javascript
jQuery超精致图片轮播幻灯片特效代码分享
2015/09/10 Javascript
jQuery实现放大镜效果实例代码
2016/03/17 Javascript
JS版微信6.0分享接口用法分析
2016/10/13 Javascript
Bootstrap实现的标签页内容切换显示效果示例
2017/05/25 Javascript
jQuery使用ajax_动力节点Java学院整理
2017/07/05 jQuery
AngularJS 中ui-view传参的实例详解
2017/08/25 Javascript
Vue中使用Sortable的示例代码
2018/04/07 Javascript
JS数据类型分类及常用判断方法
2020/11/19 Javascript
[03:12]2016完美“圣”典风云人物:单车专访
2016/12/02 DOTA
Python中shutil模块的常用文件操作函数用法示例
2016/07/05 Python
发布你的Python模块详解
2016/09/15 Python
python MySQLdb使用教程详解
2018/03/20 Python
OpenCV HSV颜色识别及HSV基本颜色分量范围
2019/03/22 Python
python super用法及原理详解
2020/01/20 Python
通过cmd进入python的步骤
2020/06/16 Python
CSS3为背景图设置遮罩并解决遮罩样式继承问题
2020/06/22 HTML / CSS
解析HTML5中的新功能本地存储localStorage
2016/03/01 HTML / CSS
美国购买体育、音乐会和剧院门票网站:SelectATicket
2019/09/08 全球购物
介绍一下write命令
2012/09/24 面试题
化学实验员岗位职责
2013/12/28 职场文书
学生个人自我鉴定范文
2014/03/28 职场文书
新教师培训方案
2014/06/08 职场文书
工作目标责任书
2014/07/23 职场文书
党员评议表自我评价范文
2014/10/20 职场文书
个人政治思想总结
2015/03/05 职场文书
烛光里的微笑观后感
2015/06/17 职场文书
高通2023 年将发布高性能PC处理器
2022/04/29 数码科技
Java线程的6种状态与生命周期
2022/05/11 Java/Android