矩阵之间无循环计算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> ...
随机推荐
- IO流3
public class Test1 { public static void main(String[] args) throws Exception { //第二个参数,表示是否向末尾追加,tru ...
- Python基础总结之第十天开始【认识一下python的另一个数据对象-----字典】(新手可相互督促)
看了大家的评论,还是有意外的收货.感谢每个小伙伴的评论与补充. 众人拾柴火焰高~ 今天的笔记是记录python中的数据对象----字典! 前面有讲到list列表和tuple元组的笔记,他们都是一样可以 ...
- git指令-未完待更新
git指令 1. $ git config --global user.name "Your Name" $ git config --global user.email &quo ...
- Java的编译原理
概述 java语言的"编译期"分为前端编译和后端编译两个阶段.前端编译是指把*.java文件转变成*.class文件的过程; 后端编译(JIT, Just In Time Comp ...
- 基于Spring注解的上下文初始化过程源码解析(一)
最近工作之余有时间和精力,加上平时对源码比较感兴趣,就开始啃起了Spring源码.为加深印象写了这篇博客,如有错误,望各位大佬不吝指正. 我看的是Spring5的源码,从同性社区download下来后 ...
- swift 分享share页面封装(功能按钮不同)
关于分享功能的页面应该有很多,写这篇swift版本的分享页面,根据不同模块可能分享的功能按钮不一样,引言: 想必大家都使用微博右上角更多按钮,会弹出如下的界面: 在开发中,可能针对同一个app的不同按 ...
- redis缓存介绍以及常见问题浅析
# 没缓存的日子: 对于web来说,是用户量和访问量支持项目技术的更迭和前进.随着服务用户提升.可能会出现一下的一些状况: 页面并发量和访问量并不多,mysql足以支撑自己逻辑业务的发展.那么其实可以 ...
- 0x33 同余
目录 定义 同余类与剩余系 费马小定理 欧拉定理 证明: 欧拉定理的推论 证明: 应用: 定义 若整数 $a$ 和整数 $b$ 除以正整数 $m$ 的余数相等,则称 $a,b$ 模 $m$ 同余,记为 ...
- ZooKeeper系列(一)—— ZooKeeper 简介及核心概念
一.Zookeeper简介 Zookeeper 是一个开源的分布式协调服务,目前由 Apache 进行维护.Zookeeper 可以用于实现分布式系统中常见的发布/订阅.负载均衡.命令服务.分布式协调 ...
- laya 下以光标为中心缩放对象
private MouseWheel(e: Laya.Event) { console.log("event"); let currentSp = e.target as Laya ...