【转载】Python Numpy求余弦值和欧几里得距离

首先

import numpy as np

求余弦值

def cosine_distance(matrix1,matrix2):
        matrix1_matrix2 = np.dot(matrix1, matrix2.transpose())

        matrix1_norm = np.sqrt(np.multiply(matrix1, matrix1).sum(axis=1))
        matrix1_norm = matrix1_norm[:, np.newaxis]

        matrix2_norm = np.sqrt(np.multiply(matrix2, matrix2).sum(axis=1))
        matrix2_norm = matrix2_norm[:, np.newaxis]

        cosine_distance = np.divide(matrix1_matrix2, np.dot(matrix1_norm, matrix2_norm.transpose()))
        return cosine_distance

求欧几里得距离

def EuclideanDistances(A, B):
    BT = B.transpose()
    vecProd = np.dot(A,BT)

    SqA =  A**2
    sumSqA = np.matrix(np.sum(SqA, axis=1))
    sumSqAEx = np.tile(sumSqA.transpose(), (1, vecProd.shape[1]))

    SqB = B**2
    sumSqB = np.sum(SqB, axis=1)
    sumSqBEx = np.tile(sumSqB, (vecProd.shape[0], 1))
 
    SqED = sumSqBEx + sumSqAEx - 2*vecProd
    SqED[SqED<0]=0.0   
    ED = np.sqrt(SqED)

    return ED

 

【转载】long long ago不知道在哪找到的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值