N点与numpy/scipy中的参考之间的有效距离计算 [英] Efficient distance calculation between N points and a reference in numpy/scipy

查看:47
本文介绍了N点与numpy/scipy中的参考之间的有效距离计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用 scipy/numpy.我有一个 100000*3 的数组,每一行是一个坐标,一个 1*3 的中心点.我想计算数组中每一行到中心的距离并将它们存储在另一个数组中.最有效的方法是什么?

I just started using scipy/numpy. I have an 100000*3 array, each row is a coordinate, and a 1*3 center point. I want to calculate the distance for each row in the array to the center and store them in another array. What is the most efficient way to do it?

推荐答案

我会看看scipy.spatial.distance.cdist:

http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html

import numpy as np
import scipy

a = np.random.normal(size=(10,3))
b = np.random.normal(size=(1,3))

dist = scipy.spatial.distance.cdist(a,b) # pick the appropriate distance metric 

dist 对于默认的距离度量相当于:

dist for the default distant metric is equivalent to:

np.sqrt(np.sum((a-b)**2,axis=1))  

尽管 cdist 对于大型数组效率更高(在我的机器上,由于您的大小问题,cdist 的速度提高了约 35 倍).

although cdist is much more efficient for large arrays (on my machine for your size problem, cdist is faster by a factor of ~35x).

这篇关于N点与numpy/scipy中的参考之间的有效距离计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆