python数组如果余弦_两个数组之间的余弦距离计算-Python

I want to apply a function fn, which is essentially cosine distance computation on two large numpy arrays of shapes (10000, 100) and (5000, 100) row-wise, i.e. i calculate a value for each combination of rows in these arrays.

My implementation :

import math

def fn(v1,v2):

sumxx, sumxy, sumyy = 0, 0, 0

for i in range(len(v1)):

x = v1[i]; y = v2[i]

sumxx += x*x

sumyy += y*y

sumxy += x*y

return sumxy/math.sqrt(sumxx*sumyy)

val = []

for i in range(array1.shape[0]):

for j in range(array2.shape[0]):

val.append(fn(array1[i, :], array2[j, :]))

The function is very fast and takes only few ms:

CPU times: user 4 ms, sys: 0 ns, total: 4 ms

Wall time: 1.24 ms

Is there any efficient way to do this?

解决方案

Approach #1 : We could simply use Scipy's cdist with its cosine distance functionality -

from scipy.spatial.distance import cdist

val_out = 1 - cdist(array1, array2, 'cosine')

Approach #2 : Another approach using matrix-multiplication -

def cosine_vectorized(array1, array2):

sumyy = (array2**2).sum(1)

sumxx = (array1**2).sum(1, keepdims=1)

sumxy = array1.dot(array2.T)

return (sumxy/np.sqrt(sumxx))/np.sqrt(sumyy)

Approach #3 : Using np.einsum to compute the self squared summations for another one -

def cosine_vectorized_v2(array1, array2):

sumyy = np.einsum('ij,ij->i',array2,array2)

sumxx = np.einsum('ij,ij->i',array1,array1)[:,None]

sumxy = array1.dot(array2.T)

return (sumxy/np.sqrt(sumxx))/np.sqrt(sumyy)

Approach #4 : Bringing in numexpr module to offload the square-root computations for another method -

import numexpr as ne

def cosine_vectorized_v3(array1, array2):

sumyy = np.einsum('ij,ij->i',array2,array2)

sumxx = np.einsum('ij,ij->i',array1,array1)[:,None]

sumxy = array1.dot(array2.T)

sqrt_sumxx = ne.evaluate('sqrt(sumxx)')

sqrt_sumyy = ne.evaluate('sqrt(sumyy)')

return ne.evaluate('(sumxy/sqrt_sumxx)/sqrt_sumyy')

Runtime test

# Using same sizes as stated in the question

In [185]: array1 = np.random.rand(10000,100)

...: array2 = np.random.rand(5000,100)

...:

In [194]: %timeit 1 - cdist(array1, array2, 'cosine')

1 loops, best of 3: 366 ms per loop

In [195]: %timeit cosine_vectorized(array1, array2)

1 loops, best of 3: 287 ms per loop

In [196]: %timeit cosine_vectorized_v2(array1, array2)

1 loops, best of 3: 283 ms per loop

In [197]: %timeit cosine_vectorized_v3(array1, array2)

1 loops, best of 3: 217 ms per loop

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值