主頁 > 知識庫 > Python 求向量的余弦值操作

Python 求向量的余弦值操作

熱門標簽:百度AI接口 語音系統(tǒng) Win7旗艦版 企業(yè)做大做強 電話運營中心 客戶服務 呼叫中心市場需求 硅谷的囚徒呼叫中心

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實現(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.T
denom = linalg.norm(A) * linalg.norm(B)
cos = num / denom #余弦值
sim = 0.5 + 0.5 * cos #歸一化  從[-1,1]到[0,1]

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

您可能感興趣的文章:
  • Python 余弦相似度與皮爾遜相關系數 計算實例
  • python代碼如何實現(xiàn)余弦相似性計算
  • 余弦相似性計算及python代碼實現(xiàn)過程解析
  • Python繪制正余弦函數圖像的方法
  • Python使用matplotlib繪制余弦的散點圖示例
  • Python使用matplotlib繪制正弦和余弦曲線的方法示例
  • python實現(xiàn)余弦相似度文本比較的示例

標簽:長沙 山西 崇左 安康 海南 喀什 山西 濟南

巨人網絡通訊聲明:本文標題《Python 求向量的余弦值操作》,本文關鍵詞  ;如發(fā)現(xiàn)本文內容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內容系統(tǒng)采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266