溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何操作Python 求向量的余弦值

發(fā)布時(shí)間:2021-03-04 15:34:55 來源:億速云 閱讀:509 作者:TREX 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“如何操作Python 求向量的余弦值”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“如何操作Python 求向量的余弦值”吧!

1、余弦相似度

余弦相似度衡量的是2個(gè)向量間的夾角大小,通過夾角的余弦值表示結(jié)果,因此2個(gè)向量的余弦相似度為:

如何操作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))) #結(jié)果顯示
cosVector([2,1],[1,1])

一個(gè)計(jì)算二維數(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]))
 
#計(jì)算query_output(60,20)和db_output(60,20)的余弦值,用60*1的向量存儲(chǔ) 
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)
--------------------------------------------------------------------------------------------
#計(jì)算query_output和db_output的余弦值,用60*1的向量存儲(chǔ)
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é)果存入文件中,并且一行一個(gè)數(shù)字
file=open('cosResult.txt','w')
for i in cosResult:
 file.write(str(i).replace('[','').replace(']','')+'\n') #\r\n為換行符 
file.close()

補(bǔ)充:python實(shí)現(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 >從[-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 求向量的余弦值”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI