矩阵之间无循环计算L2距离
实现两个矩阵的无循环计算欧氏距离 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: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距离的更多相关文章
- js计算元素距离顶部的高度及元素是否在可视区判断
前言: 在业务当中,我们经常要计算元素的大小和元素在页面的位置信息.比如说,在一个滚动区域内,我要知道元素A是在可视区内,还是在隐藏内容区(滚动到外边看不到了).有时还要进一步知道,元素是全部都显示在 ...
- js根据经纬度计算两点距离
js版-胡老师 google.maps.LatLng.prototype.distanceFrom = function(latlng) { var lat = [this.lat(), lat ...
- PyTorch 实战:计算 Wasserstein 距离
PyTorch 实战:计算 Wasserstein 距离 2019-09-23 18:42:56 This blog is copied from: https://mp.weixin.qq.com/ ...
- 【百度地图API】如何根据摩卡托坐标进行POI查询,和计算两点距离
原文:[百度地图API]如何根据摩卡托坐标进行POI查询,和计算两点距离 摘要: 百度地图API有两种坐标系,一种是百度经纬度,一种是摩卡托坐标系.在本章你将学会: 1.如何相互转换这两种坐标: 2. ...
- Spark Java API 计算 Levenshtein 距离
Spark Java API 计算 Levenshtein 距离 在上一篇文章中,完成了Spark开发环境的搭建,最终的目标是对用户昵称信息做聚类分析,找出违规的昵称.聚类分析需要一个距离,用来衡量两 ...
- numpy计算路线距离
numpy计算路线距离 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考文献 enumerate遍历数组 np.diff函数 numpy适用数组作为索引 标记路线上的点 \[X={X1,X ...
- 什么是Docker—无服务器计算服务
什么是Docker https://mp.weixin.qq.com/s?__biz=MzU0Mzk1OTU2Mg==&mid=2247483881&idx=1&sn=aa27 ...
- HDU 2276 Kiki & Little Kiki 2( 矩阵快速幂 + 循环同构矩阵 )
蒟蒻的我还需深入学习 链接:传送门 题意:给出一个长度为 n,n 不超过100的 01 串 s ,每当一个数字左侧为 1 时( 0的左侧是 n-1 ),这个数字就会发生改变,整个串改变一次需要 1s ...
- geolocation获取当前位置显示及计算两地距离
获取当前经纬度 利用HTML5(以及基于JavaScript的地理定位API),可以很容易地在页面中访问位置信息,下面代码,就可以简单的获取当前位置信息: <!DOCTYPE html> ...
随机推荐
- web设计之无懈可击
无懈可击的web设计旨在尽可能地考虑页面元素在各个情况下都能够呈现最好的效果. 1. 思路总览 2. 灵活的文字 3. 可伸缩的导航栏 4. 可扩展的行 5. 自由的框式组件 6. 图片/标题/说明文 ...
- 前端js性能优化的要点
1 尽量少使用全局查找,比如全局变量,如果要多次使用,可以将全局变量存为局部变量再使用 eg:function(){ var body=document.body; alert(body): body ...
- jenkins未授权访问漏洞
jenkins未授权访问漏洞 一.漏洞描述 未授权访问管理控制台,可以通过脚本命令行执行系统命令.通过该漏洞,可以后台管理服务,通过脚本命令行功能执行系统命令,如反弹shell,wget写webshe ...
- .net core 基于 IHostedService 实现定时任务
.net core 基于 IHostedService 实现定时任务 Intro 从 .net core 2.0 开始,开始引入 IHostedService,可以通过 IHostedService ...
- S2:java集合框架
Java集合就是一个容器.面向对象语言对事物的体现都是以对象的形式存在,所以为了方便对多个对象的操作,就对对象进行存储,集合就是存储对象最常用的一种方式.集合只用于存储对象,集合长度是可变的,集合可以 ...
- JavaScript数据结构——字典和散列表的实现
在前一篇文章中,我们介绍了如何在JavaScript中实现集合.字典和集合的主要区别就在于,集合中数据是以[值,值]的形式保存的,我们只关心值本身:而在字典和散列表中数据是以[键,值]的形式保存的,键 ...
- Fork 多进程 模拟并行访问web service获取响应时间差
#include <ros/ros.h> #include <iostream> #include <string> #include <cstring> ...
- JS和C#.NET获取客户端IP
我们经常在项目中会遇到这种需要获取客户端真实IP的需求,其实在网上也能随便就能查到各种获取的方法,我也是在网上查了加上了自己的实践,说一下自己在实践后的感受,基本上网上大部分都是用JS的方法来获取客户 ...
- .net core web api部署到Linux系统CentOS 7
一.创建一个.net core web api 的Demo 完成后的项目结构如图 修改下监听端口 发布代码 二.发布到CentOS 7上并运行 下一步需要一定的虚拟机知识了,我这里使用了windows ...
- java web 加载Spring --web.xml 篇
spring是目前最流行的框架.今天谈谈对spring的认识 起步 javaweb中我们首先会遇到的配置文件就是web.xml,这是javaweb为我们封装的逻辑,不在今天的研究中.略过,下面是一个标 ...