实现两个矩阵的无循环计算欧氏距离 Euclidean distance

navigation:

*[1.问题描述](#1.problems sources)

*[2.解决方法](#2.no loop cal the distances)

1.问题来源

kNN算法中会计算两个矩阵的距离

可以使用循环的方法来实现,效率较低

def compute_distances_one_loop(self, X):
"""
train:5000x3072
test: 500x3072
- X: A numpy array of shape (num_test, D) containing test data
Returns:
- dists: A numpy array of shape (num_test, num_train) where dists[i, j]
is the Euclidean distance between the ith test point and the jth training
point.
"""
num_test = X.shape[0]
num_train = self.X_train.shape[0]
dists = np.zeros((num_test, num_train))
for i in range(num_test):
#######################################################################
# TODO: #
# Compute the l2 distance between the ith test point and all training #
# points, and store the result in dists[i, :]. #
#######################################################################
distance=np.sqrt(np.sum(np.square(self.X_train - X[i,:]),axis=1))
dists[i,:]=distance
return dists

2.无循环计算L2 distances

一眼看到这个代码,真的是被深深折服!厉害,值得细细学习搞懂。

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. #
######################################################################### M = np.dot(X, self.X_train.T)
nrow=M.shape[0]
ncol=M.shape[1]
te = np.diag(np.dot(X,X.T))
tr = np.diag(np.dot(self.X_train,self.X_train.T))
te= np.reshape(np.repeat(te,ncol),M.shape)
tr = np.reshape(np.repeat(tr, nrow), M.T.shape)
sq=-2 * M +te+tr.T
dists = np.sqrt(sq) return dists

可能一下子有点懵,不着急 我们举个例子一步一步理解

要先知道计算L2的距离公式:

\[L2(x_{i},x_{j})=(\sum_{i=1}^{n} \mid x_{i}^{(l)} - x_{j}^{(l)} \mid ^{2})^{\frac{1}{2}}
\]

计算L2距离需要得到 两点距离差的平方和的开方

再熟悉一个基本公式

\[(a-b)^{2}= a^{2}- 2ab+b^{2}
\]

# 假设 x:4x3  ,y: 2x3
# 最后输出一个 2x4矩阵
import numpy as np
>>> x=np.array([[1,2,3],[3,4,5],[5,6,7],[7,8,9]])
>>> x
array([[1, 2, 3],
[3, 4, 5],
[5, 6, 7],
[7, 8, 9]])
>>> y=np.array([[2,3,4],[1,2,3]])
>>> y
array([[2, 3, 4],
[1, 2, 3]])
# 计算两个矩阵的乘积
>>> M=np.dot(y,x.T)
>>> M
array([[20, 38, 56, 74],
[14, 26, 38, 50]])
# 保存乘积矩阵的行列
>>> nrow=M.shape[0]
>>> ncol=M.shape[1]
>>> nrow
2
>>> ncol
4

先计算,提取出对角元素

>>> te=np.diag(np.dot(y,y.T))
>>> tr=np.diag(np.dot(x,x.T))
>>> te
array([29, 14])
>>> tr
array([ 14, 50, 110, 194])

按对角元素来进行扩充,满足矩阵计算要求

得到\(a^{2}\),\(b^{2}\)

# 继续整理
>>> te=np.reshape(np.repeat(te,ncol),M.shape) # ncol:4 ,M: 2x4
>>> tr=np.reshape(np.repeat(tr,nrow),M.T.shape) #nrow:2 ,M.T:4x2
>>> te
array([[29, 29, 29, 29],
[14, 14, 14, 14]])
>>> tr
array([[ 14, 14],
[ 50, 50],
[110, 110],
[194, 194]])

\(-2ab\)就是-2*M

计算距离的开方

>>> sq=-2*M+te+tr.T
>>> dists=np.sqrt(sq)
>>> sq
array([[ 3, 3, 27, 75],
[ 0, 12, 48, 108]])
>>> dists
array([[ 1.73205081, 1.73205081, 5.19615242, 8.66025404],
[ 0. , 3.46410162, 6.92820323, 10.39230485]])

矩阵之间无循环计算L2距离的更多相关文章

  1. js计算元素距离顶部的高度及元素是否在可视区判断

    前言: 在业务当中,我们经常要计算元素的大小和元素在页面的位置信息.比如说,在一个滚动区域内,我要知道元素A是在可视区内,还是在隐藏内容区(滚动到外边看不到了).有时还要进一步知道,元素是全部都显示在 ...

  2. js根据经纬度计算两点距离

    js版-胡老师 google.maps.LatLng.prototype.distanceFrom = function(latlng) {    var lat = [this.lat(), lat ...

  3. PyTorch 实战:计算 Wasserstein 距离

    PyTorch 实战:计算 Wasserstein 距离 2019-09-23 18:42:56 This blog is copied from: https://mp.weixin.qq.com/ ...

  4. 【百度地图API】如何根据摩卡托坐标进行POI查询,和计算两点距离

    原文:[百度地图API]如何根据摩卡托坐标进行POI查询,和计算两点距离 摘要: 百度地图API有两种坐标系,一种是百度经纬度,一种是摩卡托坐标系.在本章你将学会: 1.如何相互转换这两种坐标: 2. ...

  5. Spark Java API 计算 Levenshtein 距离

    Spark Java API 计算 Levenshtein 距离 在上一篇文章中,完成了Spark开发环境的搭建,最终的目标是对用户昵称信息做聚类分析,找出违规的昵称.聚类分析需要一个距离,用来衡量两 ...

  6. numpy计算路线距离

    numpy计算路线距离 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考文献 enumerate遍历数组 np.diff函数 numpy适用数组作为索引 标记路线上的点 \[X={X1,X ...

  7. 什么是Docker—无服务器计算服务

    什么是Docker https://mp.weixin.qq.com/s?__biz=MzU0Mzk1OTU2Mg==&mid=2247483881&idx=1&sn=aa27 ...

  8. HDU 2276 Kiki & Little Kiki 2( 矩阵快速幂 + 循环同构矩阵 )

    蒟蒻的我还需深入学习 链接:传送门 题意:给出一个长度为 n,n 不超过100的 01 串 s ,每当一个数字左侧为 1 时( 0的左侧是 n-1 ),这个数字就会发生改变,整个串改变一次需要 1s ...

  9. geolocation获取当前位置显示及计算两地距离

    获取当前经纬度 利用HTML5(以及基于JavaScript的地理定位API),可以很容易地在页面中访问位置信息,下面代码,就可以简单的获取当前位置信息: <!DOCTYPE html> ...

随机推荐

  1. jQuery 小测试

    1.在div元素中,包含了一个<span>元素,通过has选择器获取<div>元素中的<span>元素的语法是? 提示使用has() 答案: $(div:has(s ...

  2. 【iOS】Signing for "project_name" requires a development team. Select a development team in the project editor

    Xcode 8.3.2 运行 GitHub 上下载的代码时报了这个错. 解决方法: 单击工程名 --> Signing --> Team --> 选择对应的Account(如果没有A ...

  3. Java秒杀系统实战系列~商品秒杀代码实战

    摘要: 本篇博文是“Java秒杀系统实战系列文章”的第六篇,本篇博文我们将进入整个秒杀系统核心功能模块的代码开发,即“商品秒杀”功能模块的代码实战. 内容: “商品秒杀”功能模块是建立在“商品详情”功 ...

  4. .net core开发从未如此简单,比abp更接地气

    在谈起java一家独大的时候,dotnet人员总是一边嘲笑大量滥竽充数的java从业者,一边羡慕人家的生态.以前是只能羡慕,现在dotnet core开源了,我们都可以为dotnet core的开原生 ...

  5. request获取url链接和参数

            //Returns the part of this request's URL from the protocol name up to the query string in th ...

  6. C# Winform 自定义控件——TextBox

    效果:   描述: 类似html标签里input标签里的placeHolder属性,控件继承TextBox,拥有一个描述提示信息的字段_txtPlaceHolder,重写了消息处理函数WndProc, ...

  7. Flink 从0到1学习 —— Flink 中如何管理配置?

    前言 如果你了解 Apache Flink 的话,那么你应该熟悉该如何像 Flink 发送数据或者如何从 Flink 获取数据.但是在某些情况下,我们需要将配置数据发送到 Flink 集群并从中接收一 ...

  8. ieda控制台缓冲区限制问题

    一.现象 控制台输出数据若超过默认值时,将从后向前取默认值大小数据(1024) 二.解决方案 1.配置文件(idea安装目录/bin/idea.properties) 2.找到该栏:idea.cycl ...

  9. 【Java例题】3.6 计算arcsin(x)的值

    6.使用泰勒展开式计算arcsin(x)的值. arcsin(x)=x+x^3/(2*3)+1*3*x^5/(2*4*5)+...+ (2n)!*x^(2n+1)/(2^2n)*(n!)^2*(2n+ ...

  10. appcan IDE 无法 请求数据

    我们4月27号从4.0.1升级到4.0.2后,IDE本地预览get请求不到数据.但是在线打包安装到手机又是正常的. 先下载 "uexXmlHttpMgr.rar",下载链接:htt ...