计算两个矩阵之间的欧式距离「建议收藏」

计算两个矩阵之间的欧式距离「建议收藏」在我们使用k-NN模型时,需要计算测试集中每一点到训练集中每一点的欧氏距离,即需要求得两矩阵之间的欧氏距离。在实现k-NN算法时通常有三种方案,分别是使用两层循环,使用一层循环和不使用循环。使用两层循环分别对训练集和测试集中的数据进行循环遍历,计算每两个点之间的欧式距离,然后赋值给dist矩阵。此算法没有经过任何优化。num_test=X.shape[0]num_…

大家好,又见面了,我是你们的朋友全栈君。

在我们使用k-NN模型时,需要计算测试集中每一点到训练集中每一点的欧氏距离,即需要求得两矩阵之间的欧氏距离。在实现k-NN算法时通常有三种方案,分别是使用两层循环,使用一层循环和不使用循环。

使用两层循环

分别对训练集和测试集中的数据进行循环遍历,计算每两个点之间的欧式距离,然后赋值给dist矩阵。此算法没有经过任何优化。

num_test = X.shape[0]
    num_train = self.X_train.shape[0]
    dists = np.zeros((num_test, num_train)) 
    for i in xrange(num_test):
      for j in xrange(num_train):
        ##################################################################### # TODO: # # Compute the l2 distance between the ith test point and the jth # # training point, and store the result in dists[i, j]. You should # # not use a loop over dimension. # #####################################################################
        # pass
        dists[i][j] = np.sqrt(np.sum(np.square(X[i] - self.X_train[j])))
        ##################################################################### # END OF YOUR CODE # #####################################################################
    return dists

使用一层循环

使用矩阵表示训练集的数据,计算测试集中每一点到训练集矩阵的距离,可以对算法优化为只使用一层循环。

def compute_distances_one_loop(self, X):
    """ Compute the distance between each test point in X and each training point in self.X_train using a single loop over the test data. Input / Output: Same as compute_distances_two_loops """
    num_test = X.shape[0]
    num_train = self.X_train.shape[0]
    dists = np.zeros((num_test, num_train))
    for i in xrange(num_test):
      ####################################################################### # TODO: # # Compute the l2 distance between the ith test point and all training # # points, and store the result in dists[i, :]. # #######################################################################
      # pass
      dists[i] = np.sqrt(np.sum(np.square(self.X_train - X[i]), axis = 1))
      ####################################################################### # END OF YOUR CODE # #######################################################################
    return dists

不使用循环

运算效率最高的算法是将训练集和测试集都使用矩阵表示,然后使用矩阵运算的方法替代之前的循环操作。但此操作需要我们对矩阵的运算规则非常熟悉。接下来着重记录如何计算两个矩阵之间的欧式距离。

记录测试集矩阵P的大小为M*D,训练集矩阵C的大小为N*D(测试集中共有M个点,每个点为D维特征向量。训练集中共有N个点,每个点为D维特征向量)
Pi P i 是P的第i行,记 Cj C j 是C的第j行
Pi=[Pi1Pi2PiD] P i = [ P i 1 P i 2 ⋯ P i D ] Cj=[Cj1Cj2CjD] C j = [ C j 1 C j 2 ⋯ C j D ]


首先计算 Pi P i Cj C j 之间的距离dist(i,j)
d(Pi,Cj)=(Pi1Cj1)2+(Pi2Cj2)2++(PiDCjD)2=(P2i1+P2i2++P2iD)+(C2j1+C2j2++C2jD)2×(Pi1Cj1+Pi2Cj2++PiDCiD)=Pi2+Cj22×PiCTj d ( P i , C j ) = ( P i 1 − C j 1 ) 2 + ( P i 2 − C j 2 ) 2 + ⋯ + ( P i D − C j D ) 2 = ( P i 1 2 + P i 2 2 + ⋯ + P i D 2 ) + ( C j 1 2 + C j 2 2 + ⋯ + C j D 2 ) − 2 × ( P i 1 C j 1 + P i 2 C j 2 + ⋯ + P i D C i D ) = ‖ P i ‖ 2 + ‖ C j ‖ 2 − 2 × P i C j T


我们可以推广到距离矩阵的第i行的计算公式
dist[i]=(Pi2Pi2Pi2)+(C12C22CN2)2×Pi(CT1CT2CTN)=(Pi2Pi2Pi2)+(C12C22CN2)2×PiCT d i s t [ i ] = ( ‖ P i ‖ 2 ‖ P i ‖ 2 ⋯ ‖ P i ‖ 2 ) + ( ‖ C 1 ‖ 2 ‖ C 2 ‖ 2 ⋯ ‖ C N ‖ 2 ) − 2 × P i ( C 1 T C 2 T ⋯ C N T ) = ( ‖ P i ‖ 2 ‖ P i ‖ 2 ⋯ ‖ P i ‖ 2 ) + ( ‖ C 1 ‖ 2 ‖ C 2 ‖ 2 ⋯ ‖ C N ‖ 2 ) − 2 × P i C T


继续将公式推广为整个距离矩阵
dist=P12P22PM2P12P22PM2P12P22PM2+C12C12C12C22C22C22CN2CN2CN22×PCT d i s t = ( ‖ P 1 ‖ 2 ‖ P 1 ‖ 2 ⋯ ‖ P 1 ‖ 2 ‖ P 2 ‖ 2 ‖ P 2 ‖ 2 ⋯ ‖ P 2 ‖ 2 ⋮ ⋮ ⋱ ⋮ ‖ P M ‖ 2 ‖ P M ‖ 2 ⋯ ‖ P M ‖ 2 ) + ( ‖ C 1 ‖ 2 ‖ C 2 ‖ 2 ⋯ ‖ C N ‖ 2 ‖ C 1 ‖ 2 ‖ C 2 ‖ 2 ⋯ ‖ C N ‖ 2 ⋮ ⋮ ⋱ ⋮ ‖ C 1 ‖ 2 ‖ C 2 ‖ 2 ⋯ ‖ C N ‖ 2 ) − 2 × P C T

表示为python代码:

def compute_distances_no_loops(self, X):
    """ Compute the distance between each test point in X and each training point in self.X_train using no explicit loops. Input / Output: Same as compute_distances_two_loops """
    num_test = X.shape[0]
    num_train = self.X_train.shape[0]
    dists = np.zeros((num_test, num_train)) 
    #########################################################################
    # TODO: #
    # Compute the l2 distance between all test points and all training #
    # points without using any explicit loops, and store the result in #
    # dists. #
    # #
    # You should implement this function using only basic array operations; #
    # in particular you should not use functions from scipy. #
    # #
    # HINT: Try to formulate the l2 distance using matrix multiplication #
    # and two broadcast sums. #
    #########################################################################
    # pass
    dists = np.sqrt(-2*np.dot(X, self.X_train.T) + np.sum(np.square(self.X_train), axis = 1) + np.transpose([np.sum(np.square(X), axis = 1)]))
    #########################################################################
    # END OF YOUR CODE #
    #########################################################################
    return dists
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/150938.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • java set集合详解

    java set集合详解参考地址:https://blog.csdn.net/qq_33642117/article/details/52040345一,SetSet:注重独一无二的性质,该体系集合可以知道某物是否已近存在于集合中,不会存储重复的元素用于存储无序(存入和取出的顺序不一定相同)元素,值不能重复。对象的相等性  引用到堆上同一个对象的两个引用是相等的。如果对两个引用调用hashCode方…

  • pycharm2021.4激活码(破解版激活)

    pycharm2021.4激活码(破解版激活),https://javaforall.cn/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

  • Web前端学习 | Ajax

    Web前端学习 | Ajaxajax其实是代替手工输入url向server申请资源的一个工具。XMLHttpRequest对象的onload回调函数是在异步请求加载完成后所执行的函数,当JavaScript监测到请求的数据全部传输完成后就会触发该函数。而open()函数设置异步请求的method、URL和同步方式等参数,执行open()后再执行send()函数才开始向服务器发送请求。<!DO…

  • APP运营:盘点八款主流 APP 消息推送工具[通俗易懂]

    APP运营:盘点八款主流 APP 消息推送工具[通俗易懂]在APP日常运营中,基于营销以及推广的目的,我们需要对APP用户推送一些活动信息或重要资讯。常见的消息推送工具分为两种:1、即技术团队自行开发;2、第三方Push工具对于许多创业型公司而言,相对于自行开发,第三方消息推送工具在推送稳定性、精确覆盖性以及成本方面更具有优势,只需要下载并集成SDK就可以实现功能。本文中我们将盘点八款主流第三方APP消息推送工具,希望对大家在A…

  • Git管理工具常用

    适用场景:通常我们到了新公司或者新的部门,一般会给你一个git的源码路径,如:http://ip:port/xxxx/xxx.git。这个时候我们需要拉取代码开发,则需要用到一些常用的工具!这里分享一下个人的经验。准备环境:1、下载两个工具(Git-2.16.2-64-bit.exe和TortoiseGit-1.8.14.0_64bit.1436148947),前者为本地…

  • 史上最详细图解快速排序的方法_快速排序的基本步骤

    史上最详细图解快速排序的方法_快速排序的基本步骤0.前言找了好多贴在都没有找到舒心的一次能看懂的文章,决定把学明白每一步全部图解出来。推荐一个博主的文章也很不错:https://blog.csdn.net/weixin_42109012/article/details/916450511.图解开始![在这里插入图片描述](https://img-blog.csdnimg.cn/e6bbdfbe97e44bbd99f99cf456c998ed.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号