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()
补充: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,向量,余弦值
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com
暂无“Python 求向量的余弦值操作”评论...
更新日志
2024年07月01日
2024年07月01日
- 《陈百强28CD合集》1979-1993 低速原抓[CUE+WAV][8.3G]
- 【蓝调摇滚】JohnHaydock-2024-StraightLineOnACurvedRoad(FLAC)
- 感受独特魅力《百万双钢琴演奏曲》5CD[WAV+CUE]
- 【古典音乐】安娜·莫福《咏叹调》美国版SACD[WAV+CUE]
- 《法拉利·汽车专用试音碟》名贵音响顶级黑胶金碟[CUE+WAV][478M]
- 群星《惠威试音碟5CD》顶级音质[CUE+APE][1.7G]
- 《101系列:百分百3CD 100首百分百经典金曲》[WAV+CUE][2.9GB]
- 群星.2004-《第八届广州国际高级音响展》HIFI珍藏版[APE+CUE]
- 红音堂《蔡琴往事系列》SQCD紫银合金5CD[wav]
- 张小英1978-可爱的人[新加坡黑胶版][WAV+CUE]
- 张小英1978-心有千千结[新加坡黑胶版][WAV+CUE]
- 谭晶《祖国万岁·作品全集》(8CD)[WAV+CUE]
- 群星.2010-《第13届汕头音响展纪念CD》非卖品[FLAC+CUE]
- 群星.2010-《第13届汕头音响展纪念CD》非卖品[FLAC+CUE]
- 吉尔·沙汉姆-《梁祝柴科夫斯基小提琴协奏曲(GilShaham)》[WAV分轨]