色综合图-色综合图片-色综合图片二区150p-色综合图区-玖玖国产精品视频-玖玖香蕉视频

您的位置:首頁技術文章
文章詳情頁

Python 求向量的余弦值操作

瀏覽:20日期:2022-06-26 13:38:52
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’) #rn為換行符 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.Tdenom = linalg.norm(A) * linalg.norm(B)cos = num / denom #余弦值sim = 0.5 + 0.5 * cos #歸一化 從[-1,1]到[0,1]

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。如有錯誤或未考慮完全的地方,望不吝賜教。

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 91啦丨国产丨 | 欧美一级特黄aa大片视频 | 亚洲成a人片在线播放 | 2019国产精品| 色噜噜狠狠大色综合 | 在线视频三区 | 在线观看一二三区 | 9191精品国产免费不久久 | 色天使色婷婷在线影院亚洲 | 亚洲一区二区三区成人 | 中文字字幕码一二区 | 久久成人免费观看草草影院 | 中文字幕亚洲视频 | 呦视频在线一区二区三区 | 国产美女一区二区三区 | 亚洲欧美国产视频 | 草草视频手机在线观看视频 | 久久亚洲欧美成人精品 | 国产精品18久久久久久vr | 怡红院日本一道日本久久 | 久久青草免费免费91线频观看 | 国产的一级毛片完整 | 亚洲综合国产一区在线 | 国产亚洲精品久久 | 国产一区精品在线观看 | 永久网站色视频在线观看免费 | 欧美另类在线观看 | 亚洲一区二区三区久久 | 国产精彩视频在线观看 | 欧美综合在线观看 | 亚洲国产一区二区三区四区 | 亚洲在成人网在线看 | 最新精品亚洲成a人在线观看 | 免费大片黄手机在线观看 | 一级做a爰片久久毛片美女 一级做a爰片久久毛片免费看 | 成人精品一区久久久久 | 91精品全国免费观看 | 色噜噜亚洲男人的天堂 | 日韩 国产 在线 | 久久 精品 一区二区 | 深夜一级毛片 |