Python 求向量的余弦值操作
余弦相似度衡量的是2個向量間的夾角大小,通過夾角的余弦值表示結(jié)果,因此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))) #結(jié)果顯示cosVector([2,1],[1,1])一個計算二維數(shù)組余弦值的例子:
#求余弦函數(shù)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))) #結(jié)果顯示 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] #行數(shù)cols=query_output.shape[1] #列數(shù)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)#將結(jié)果存入文件中,并且一行一個數(shù)字file=open(’cosResult.txt’,’w’)for i in cosResult: file.write(str(i).replace(’[’,’’).replace(’]’,’’)+’n’) #rn為換行符 file.close()
補充:python實現(xiàn)余弦近似度
方法一: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]
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章:
1. Python獲取抖音關(guān)注列表封號賬號的實現(xiàn)代碼2. ajax請求添加自定義header參數(shù)代碼3. Python數(shù)據(jù)分析之pandas函數(shù)詳解4. 解決Python 進程池Pool中一些坑5. php測試程序運行速度和頁面執(zhí)行速度的代碼6. 無線標記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁7. 三個不常見的 HTML5 實用新特性簡介8. 使用.net core 自帶DI框架實現(xiàn)延遲加載功能9. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究10. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析
