Programing

NumPy로 유클리드 거리를 어떻게 계산할 수 있습니까?

lottogame 2020. 2. 16. 19:13
반응형

NumPy로 유클리드 거리를 어떻게 계산할 수 있습니까?


3D로 두 가지 점이 있습니다.

(xa, ya, za)
(xb, yb, zb)

그리고 거리를 계산하고 싶습니다 :

dist = sqrt((xa-xb)^2 + (ya-yb)^2 + (za-zb)^2)

NumPy 또는 일반적으로 Python 으로이 작업을 수행하는 가장 좋은 방법은 무엇입니까? 나는 가지고있다:

a = numpy.array((xa ,ya, za))
b = numpy.array((xb, yb, zb))

사용 numpy.linalg.norm:

dist = numpy.linalg.norm(a-b)

뒤에있는 이론 : 데이터 마이닝 소개에서 찾을 수 있습니다.

이것은 유클리드 거리l2 규범 이고 numpy.linalg.norm ord 매개 변수의 기본값이 2 이기 때문에 작동합니다 .

여기에 이미지 설명을 입력하십시오


SciPy에는 그 기능이 있습니다. 유클리드 라고 합니다.

예:

from scipy.spatial import distance
a = (1, 2, 3)
b = (4, 5, 6)
dst = distance.euclidean(a, b)

한 번에 여러 거리를 계산하는 데 관심이있는 사람은 perfplot (작은 프로젝트)을 사용하여 약간 비교했습니다 .

첫 번째 조언은 배열이 차원을 갖도록 (3, n)(그리고 분명히 C 연속적) 데이터를 구성하는 것 입니다. 연속적인 1 차원에서 덧셈이 발생하면 일이 더 빠르며 sqrt-sumwith axis=0, linalg.normwith axis=0또는 with 를 사용하면 너무 중요하지 않습니다.

a_min_b = a - b
numpy.sqrt(numpy.einsum('ij,ij->j', a_min_b, a_min_b))

약간의 마진으로 가장 빠른 변형입니다. (실제로 한 행에도 적용됩니다.)

두 번째 축에 대해 요약되는 변형 axis=1은 모두 실질적으로 느립니다.

여기에 이미지 설명을 입력하십시오


줄거리를 재현하는 코드 :

import numpy
import perfplot
from scipy.spatial import distance


def linalg_norm(data):
    a, b = data[0]
    return numpy.linalg.norm(a - b, axis=1)


def linalg_norm_T(data):
    a, b = data[1]
    return numpy.linalg.norm(a - b, axis=0)


def sqrt_sum(data):
    a, b = data[0]
    return numpy.sqrt(numpy.sum((a - b) ** 2, axis=1))


def sqrt_sum_T(data):
    a, b = data[1]
    return numpy.sqrt(numpy.sum((a - b) ** 2, axis=0))


def scipy_distance(data):
    a, b = data[0]
    return list(map(distance.euclidean, a, b))


def sqrt_einsum(data):
    a, b = data[0]
    a_min_b = a - b
    return numpy.sqrt(numpy.einsum("ij,ij->i", a_min_b, a_min_b))


def sqrt_einsum_T(data):
    a, b = data[1]
    a_min_b = a - b
    return numpy.sqrt(numpy.einsum("ij,ij->j", a_min_b, a_min_b))


def setup(n):
    a = numpy.random.rand(n, 3)
    b = numpy.random.rand(n, 3)
    out0 = numpy.array([a, b])
    out1 = numpy.array([a.T, b.T])
    return out0, out1


perfplot.save(
    "norm.png",
    setup=setup,
    n_range=[2 ** k for k in range(22)],
    kernels=[
        linalg_norm,
        linalg_norm_T,
        scipy_distance,
        sqrt_sum,
        sqrt_sum_T,
        sqrt_einsum,
        sqrt_einsum_T,
    ],
    logx=True,
    logy=True,
    xlabel="len(x), len(y)",
)

이 문제 해결 방법 의 또 다른 예는 다음같습니다 .

def dist(x,y):   
    return numpy.sqrt(numpy.sum((x-y)**2))

a = numpy.array((xa,ya,za))
b = numpy.array((xb,yb,zb))
dist_a_b = dist(a,b)

다양한 성능 메모로 간단한 답변에 대해 설명하고 싶습니다. np.linalg.norm은 아마도 필요한 것보다 더 많은 것을 할 것입니다 :

dist = numpy.linalg.norm(a-b)

첫째 -이 기능에서의 거리를 비교하기 위해, 예를 목록을 통해 일을하고 모든 값을 반환하도록 설계 pA점의 세트 sP:

sP = set(points)
pA = point
distances = np.linalg.norm(sP - pA, ord=2, axis=1.)  # 'distances' is a list

몇 가지 사항을 기억하십시오.

  • 파이썬 함수 호출은 비싸다.
  • [일반] 파이썬은 이름 조회를 캐시하지 않습니다.

그래서

def distance(pointA, pointB):
    dist = np.linalg.norm(pointA - pointB)
    return dist

보이는 것처럼 결백하지 않습니다.

>>> dis.dis(distance)
  2           0 LOAD_GLOBAL              0 (np)
              2 LOAD_ATTR                1 (linalg)
              4 LOAD_ATTR                2 (norm)
              6 LOAD_FAST                0 (pointA)
              8 LOAD_FAST                1 (pointB)
             10 BINARY_SUBTRACT
             12 CALL_FUNCTION            1
             14 STORE_FAST               2 (dist)

  3          16 LOAD_FAST                2 (dist)
             18 RETURN_VALUE

첫째, 호출 할 때마다 "np"에 대한 전역 조회, "linalg"에 대한 범위 조회 및 "norm"에 대한 범위 조회를 수행해야하며 단순히 함수 호출오버 헤드 가 수십 개의 파이썬과 동일 할 수 있습니다. 명령.

마지막으로 결과를 저장하고 다시로드하기 위해 두 가지 작업을 낭비했습니다 ...

개선시 첫 단계 : 조회 속도를 높이고 상점을 건너 뜁니다.

def distance(pointA, pointB, _norm=np.linalg.norm):
    return _norm(pointA - pointB)

훨씬 간소화되었습니다.

>>> dis.dis(distance)
  2           0 LOAD_FAST                2 (_norm)
              2 LOAD_FAST                0 (pointA)
              4 LOAD_FAST                1 (pointB)
              6 BINARY_SUBTRACT
              8 CALL_FUNCTION            1
             10 RETURN_VALUE

그러나 함수 호출 오버 헤드는 여전히 일부 작업에 해당합니다. 그리고 자신이 수학을 더 잘 수행 할 수 있는지 판단하기 위해 벤치 마크를 수행하고 싶을 것입니다.

def distance(pointA, pointB):
    return (
        ((pointA.x - pointB.x) ** 2) +
        ((pointA.y - pointB.y) ** 2) +
        ((pointA.z - pointB.z) ** 2)
    ) ** 0.5  # fast sqrt

일부 플랫폼에서는 **0.5보다 빠릅니다 math.sqrt. 귀하의 마일리지가 다를 수 있습니다.

**** 고급 성능 정보.

왜 거리를 계산합니까? 유일한 목적으로 표시하는 경우

 print("The target is %.2fm away" % (distance(a, b)))

를 따라 이동. 그러나 거리를 비교하거나 범위 검사 등을 수행하는 경우 유용한 성능 관찰을 추가하고 싶습니다.

거리를 기준으로 정렬하거나 범위 제약 조건을 충족하는 항목으로 목록을 컬링하는 두 가지 경우를 살펴 보겠습니다.

# Ultra naive implementations. Hold onto your hat.

def sort_things_by_distance(origin, things):
    return things.sort(key=lambda thing: distance(origin, thing))

def in_range(origin, range, things):
    things_in_range = []
    for thing in things:
        if distance(origin, thing) <= range:
            things_in_range.append(thing)

가장 먼저 기억해야 할 것은 피타고라스 를 사용하여 거리 ( dist = sqrt(x^2 + y^2 + z^2)) 를 계산하여 많은 sqrt통화를하고 있다는 것입니다. 수학 101 :

dist = root ( x^2 + y^2 + z^2 )
:.
dist^2 = x^2 + y^2 + z^2
and
sq(N) < sq(M) iff M > N
and
sq(N) > sq(M) iff N > M
and
sq(N) = sq(M) iff N == M

간단히 말해 실제로 X ^ 2가 아닌 X 단위로 거리가 필요할 때까지 계산에서 가장 어려운 부분을 제거 할 수 있습니다.

# Still naive, but much faster.

def distance_sq(left, right):
    """ Returns the square of the distance between left and right. """
    return (
        ((left.x - right.x) ** 2) +
        ((left.y - right.y) ** 2) +
        ((left.z - right.z) ** 2)
    )

def sort_things_by_distance(origin, things):
    return things.sort(key=lambda thing: distance_sq(origin, thing))

def in_range(origin, range, things):
    things_in_range = []

    # Remember that sqrt(N)**2 == N, so if we square
    # range, we don't need to root the distances.
    range_sq = range**2

    for thing in things:
        if distance_sq(origin, thing) <= range_sq:
            things_in_range.append(thing)

두 함수 모두 더 이상 고가의 제곱근을 수행하지 않습니다. 훨씬 빠릅니다. in_range를 발전기로 변환하여 향상시킬 수도 있습니다.

def in_range(origin, range, things):
    range_sq = range**2
    yield from (thing for thing in things
                if distance_sq(origin, thing) <= range_sq)

다음과 같은 일을 할 때 특히 이점이 있습니다.

if any(in_range(origin, max_dist, things)):
    ...

하지만 다음에해야 할 일에 거리가 필요한 경우

for nearby in in_range(origin, walking_distance, hotdog_stands):
    print("%s %.2fm" % (nearby.name, distance(origin, nearby)))

튜플 생성을 고려하십시오.

def in_range_with_dist_sq(origin, range, things):
    range_sq = range**2
    for thing in things:
        dist_sq = distance_sq(origin, thing)
        if dist_sq <= range_sq: yield (thing, dist_sq)

이것은 거리 점검을 연쇄 할 수있는 경우에 특히 유용합니다 ( '거리를 다시 계산할 필요가 없기 때문에 X 근처에 있고 Y의 Nm 내에있는 것을 찾으십시오').

그러나 우리가 정말로 큰 목록을 검색 things하고 많은 것을 고려할 가치가 없다면 어떻게해야 할까요?

실제로 매우 간단한 최적화가 있습니다.

def in_range_all_the_things(origin, range, things):
    range_sq = range**2
    for thing in things:
        dist_sq = (origin.x - thing.x) ** 2
        if dist_sq <= range_sq:
            dist_sq += (origin.y - thing.y) ** 2
            if dist_sq <= range_sq:
                dist_sq += (origin.z - thing.z) ** 2
                if dist_sq <= range_sq:
                    yield thing

이것이 유용한 지 여부는 '사물'의 크기에 달려 있습니다.

def in_range_all_the_things(origin, range, things):
    range_sq = range**2
    if len(things) >= 4096:
        for thing in things:
            dist_sq = (origin.x - thing.x) ** 2
            if dist_sq <= range_sq:
                dist_sq += (origin.y - thing.y) ** 2
                if dist_sq <= range_sq:
                    dist_sq += (origin.z - thing.z) ** 2
                    if dist_sq <= range_sq:
                        yield thing
    elif len(things) > 32:
        for things in things:
            dist_sq = (origin.x - thing.x) ** 2
            if dist_sq <= range_sq:
                dist_sq += (origin.y - thing.y) ** 2 + (origin.z - thing.z) ** 2
                if dist_sq <= range_sq:
                    yield thing
    else:
        ... just calculate distance and range-check it ...

그리고 다시 dist_sq를 산출하는 것을 고려하십시오. 핫도그 예제는 다음과 같습니다.

# Chaining generators
info = in_range_with_dist_sq(origin, walking_distance, hotdog_stands)
info = (stand, dist_sq**0.5 for stand, dist_sq in info)
for stand, dist in info:
    print("%s %.2fm" % (stand, dist))

다음과 같이 수행 할 수 있습니다. 나는 그것이 얼마나 빠른지 모르겠지만 NumPy를 사용하지 않습니다.

from math import sqrt
a = (1, 2, 3) # Data point 1
b = (4, 5, 6) # Data point 2
print sqrt(sum( (a - b)**2 for a, b in zip(a, b)))

matplotlib.mlab에서 'dist'함수를 찾았지만 충분히 유용하다고 생각하지 않습니다.

참고 용으로 여기에 게시하고 있습니다.

import numpy as np
import matplotlib as plt

a = np.array([1, 2, 3])
b = np.array([2, 3, 4])

# Distance between a and b
dis = plt.mlab.dist(a, b)

시작시 Python 3.8, math모듈은 dist함수를 직접 제공하여 두 점 사이의 유클리드 거리를 반환합니다 (튜플 또는 좌표 목록으로 제공됨).

from math import dist

dist((1, 2, 6), (-2, 3, 2)) # 5.0990195135927845

그리고 목록으로 작업하는 경우 :

dist([1, 2, 6], [-2, 3, 2]) # 5.0990195135927845

벡터를 빼고 내적을 빼면됩니다.

당신의 모범에 따라

a = numpy.array((xa, ya, za))
b = numpy.array((xb, yb, zb))

tmp = a - b
sum_squared = numpy.dot(tmp.T, tmp)
result sqrt(sum_squared)

간단한 코드이며 이해하기 쉽습니다.


나는 np.dot(도트 제품)을 좋아 한다.

a = numpy.array((xa,ya,za))
b = numpy.array((xb,yb,zb))

distance = (np.dot(a-b,a-b))**.5

ab당신이 그들을 정의, 당신은 또한 사용할 수 있습니다 :

distance = np.sqrt(np.sum((a-b)**2))

좋은 원 라이너 :

dist = numpy.linalg.norm(a-b)

그러나 속도가 문제가된다면 기계를 시험해 보는 것이 좋습니다. 내가 사용하는 것을 발견 math라이브러리를 sqrt**사각형에 대한 조작하면 한 줄 NumPy와의 솔루션보다 내 컴퓨터에 훨씬 더 빠릅니다.

이 간단한 프로그램을 사용하여 테스트를 실행했습니다.

#!/usr/bin/python
import math
import numpy
from random import uniform

def fastest_calc_dist(p1,p2):
    return math.sqrt((p2[0] - p1[0]) ** 2 +
                     (p2[1] - p1[1]) ** 2 +
                     (p2[2] - p1[2]) ** 2)

def math_calc_dist(p1,p2):
    return math.sqrt(math.pow((p2[0] - p1[0]), 2) +
                     math.pow((p2[1] - p1[1]), 2) +
                     math.pow((p2[2] - p1[2]), 2))

def numpy_calc_dist(p1,p2):
    return numpy.linalg.norm(numpy.array(p1)-numpy.array(p2))

TOTAL_LOCATIONS = 1000

p1 = dict()
p2 = dict()
for i in range(0, TOTAL_LOCATIONS):
    p1[i] = (uniform(0,1000),uniform(0,1000),uniform(0,1000))
    p2[i] = (uniform(0,1000),uniform(0,1000),uniform(0,1000))

total_dist = 0
for i in range(0, TOTAL_LOCATIONS):
    for j in range(0, TOTAL_LOCATIONS):
        dist = fastest_calc_dist(p1[i], p2[j]) #change this line for testing
        total_dist += dist

print total_dist

내 컴퓨터에서 math_calc_dist훨씬보다 빠른 실행 numpy_calc_dist: 1.5 초23.5 초 .

사이에 측정 가능한 차이를 얻으려면 fastest_calc_distmath_calc_distI 최대했다 TOTAL_LOCATIONS그리고 6000에 fastest_calc_dist소요 ~ 50 초 동안 math_calc_dist소요 ~ 60 초 .

또한 실험 할 수 numpy.sqrtnumpy.square두 불구하고보다 느린했다 math내 컴퓨터에 대안.

내 테스트는 Python 2.6.6으로 실행되었습니다.


다음은 파이썬에서 목록으로 표시된 두 점이 주어지면 파이썬에서 유클리드 거리에 대한 간결한 코드입니다.

def distance(v1,v2): 
    return sum([(x-y)**2 for (x,y) in zip(v1,v2)])**(0.5)

import numpy as np
from scipy.spatial import distance
input_arr = np.array([[0,3,0],[2,0,0],[0,1,3],[0,1,2],[-1,0,1],[1,1,1]]) 
test_case = np.array([0,0,0])
dst=[]
for i in range(0,6):
    temp = distance.euclidean(test_case,input_arr[i])
    dst.append(temp)
print(dst)

import math

dist = math.hypot(math.hypot(xa-xb, ya-yb), za-zb)

수식을 쉽게 사용할 수 있습니다

distance = np.sqrt(np.sum(np.square(a-b)))

실제로 피타고라스의 정리를 사용하여 거리를 계산하는 것보다 Δx, Δy 및 Δz의 제곱을 더하고 결과를 근절하는 것 이상은 없습니다.


다차원 공간에 대한 유클리드 거리를 계산하십시오.

 import math

 x = [1, 2, 6] 
 y = [-2, 3, 2]

 dist = math.sqrt(sum([(xi-yi)**2 for xi,yi in zip(x, y)]))
 5.0990195135927845

먼저 두 행렬의 차이를 찾으십시오. 그런 다음 numpy의 multiply 명령으로 요소 별 곱셈을 적용하십시오. 그런 다음 요소와 곱한 새 행렬의 합을 찾으십시오. 마지막으로, 합계의 제곱근을 찾으십시오.

def findEuclideanDistance(a, b):
    euclidean_distance = a - b
    euclidean_distance = np.sum(np.multiply(euclidean_distance, euclidean_distance))
    euclidean_distance = np.sqrt(euclidean_distance)
    return euclidean_distance

참고 URL : https://stackoverflow.com/questions/1401712/how-can-the-euclidean-distance-be-calculated-with-numpy



반응형