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

计算两个矩阵之间的欧式距离「建议收藏」在我们使用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=[Pi1Pi2⋯PiD] P i = [ P i 1 P i 2 ⋯ P i D ]   Cj=[Cj1Cj2⋯CjD] C j = [ C j 1 C j 2 ⋯ C j D ]


首先计算 Pi P i 和 Cj C j 之间的距离dist(i,j)
d(Pi,Cj)=(Pi1−Cj1)2+(Pi2−Cj2)2+⋯+(PiD−CjD)2−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−√=(P2i1+P2i2+⋯+P2iD)+(C2j1+C2j2+⋯+C2jD)−2×(Pi1Cj1+Pi2Cj2+⋯+PiDCiD)−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−√=∥Pi∥2+∥Cj∥2−2×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]=(∥Pi∥2∥Pi∥2⋯∥Pi∥2)+(∥C1∥2∥C2∥2⋯∥CN∥2)−2×Pi(CT1CT2⋯CTN)−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−√=(∥Pi∥2∥Pi∥2⋯∥Pi∥2)+(∥C1∥2∥C2∥2⋯∥CN∥2)−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=⎛⎝⎜⎜⎜⎜⎜⎜∥P1∥2∥P2∥2⋮∥PM∥2∥P1∥2∥P2∥2⋮∥PM∥2⋯⋯⋱⋯∥P1∥2∥P2∥2⋮∥PM∥2⎞⎠⎟⎟⎟⎟⎟⎟+⎛⎝⎜⎜⎜⎜⎜⎜∥C1∥2∥C1∥2⋮∥C1∥2∥C2∥2∥C2∥2⋮∥C2∥2⋯⋯⋱⋯∥CN∥2∥CN∥2⋮∥CN∥2⎞⎠⎟⎟⎟⎟⎟⎟−2×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
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

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

赞 (0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • java设置响应状态码

    java设置响应状态码1.各种状态码设置https://blog.csdn.net/daichangxia/article/details/781393242.设置状态码通过HttpServletResponse的方法进行返回相应的状态码,方法有如下:publicvoidsetStatus(intstatusCode)该方法设置一个任意的状态码。setStatus方法接受一个int(状态码)作为参数。如…

    2022年5月12日
  • haproxy配置详解_核心交换机配置教程

    haproxy配置详解_核心交换机配置教程Linux Haproxy详细配置教程

    2022年4月20日
  • jsp中重定向与转发的区别_jsp重定向语句是什么

    jsp中重定向与转发的区别_jsp重定向语句是什么jsp中重定向和转发的区别:

    2022年9月7日
  • malloc函数实现过程

    malloc函数实现过程在C语言中,要进行动态内存的开辟就需要使用到malloc函数,在C++中使用的new关键字的基层也是调用了malloc函数,可见malloc函数的重要性,这个就浅析一下malloc的实现过程。本文的测试环境是win10+vs2015。首先先看看malloc函数怎么去调用//malloc函数原型//void*malloc(size_tsize);//(MSDN中的定义)type

    2022年5月7日
  • 删除链表倒数第n个节点_求链表的倒数第m个元素

    删除链表倒数第n个节点_求链表的倒数第m个元素原题链接给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。进阶:你能尝试使用一趟扫描实现吗?示例 1:输入:head = [1,2,3,4,5], n = 2输出:[1,2,3,5]示例 2:输入:head = [1], n = 1输出:[]示例 3:输入:head = [1,2], n = 1输出:[1]提示:链表中结点的数目为 sz1 <= sz <= 300 <= Node.val <= 1001 <= n <= s

    2022年8月9日
  • Linux查看redis版本(查看mongodb版本)

    快半年没有在Linux中使用redis了,命令有些生疏了,网上很多博文也不对,不知道博主是否直接复制的来的。以下为重新整理资料,便于忘记时候复习首先进入cd/usr/local目录不用说了我把redis安装到了redis文件夹中了,在bin目录下找到redis-server使用./redis-server–version查看版本信息[red@RedFaceloc…

    2022年4月16日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

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