요소 별 동일성을 위해 두 개의 numpy 배열 비교
평등이 개 NumPy와 배열을 비교하는 가장 간단한 방법은 무엇입니까 (평등과 같이 정의된다 : A = B의 IFF 모든 인덱스 I를 위해 : A[i] == B[i]
)?
간단히 사용 ==
하면 부울 배열이 제공됩니다.
>>> numpy.array([1,1,1]) == numpy.array([1,1,1])
array([ True, True, True], dtype=bool)
and
배열이 동일한 지 또는 비교할 수있는 더 간단한 방법이 있는지 확인하려면이 배열의 요소에 있어야 합니까?
(A==B).all()
배열의 모든 값 (A == B)이 True인지 테스트합니다.
편집 (dbaupp의 답변과 yoavram의 의견에서)
다음 사항에 유의하십시오.
- 이 솔루션은 특정 경우에 이상한 동작을 가질 수 있습니다.
A
또는B
비어 있거나 다른 요소에 단일 요소가 포함되어 있으면를 반환True
합니다. 어떤 이유로 든 비교A==B
는 빈 배열을all
반환 하며 연산자는를 반환합니다True
. - 경우에 또 다른 위험이
A
와B
같은 모양을 가지고 있지 및 캐스트 가능한하지 않는,이 방법은 오류가 발생합니다.
결론적으로, 내가 제안 된 솔루션은 내가 생각하지만, 당신이에 대한 의심이있는 경우, 표준 하나입니다 A
및 B
전문 기능의 사용을 : 단순히 모양이나 안전 할 :
np.array_equal(A,B) # test if same shape, same elements values
np.array_equiv(A,B) # test if broadcastable shape, same elements values
np.allclose(A,B,...) # test if same shape, elements have close enough values
이 (A==B).all()
솔루션은 매우 깔끔하지만이 작업에는 몇 가지 기본 제공 기능이 있습니다. 즉 array_equal
, allclose
와 array_equiv
.
(단, 몇 가지 빠른 테스트를 수행 timeit
하면 (A==B).all()
메서드가 가장 빠르며 완전히 새로운 배열을 할당해야하기 때문에 조금 독특합니다.)
다음 코드를 사용하여 성능을 측정 해 봅시다.
import numpy as np
import time
exec_time0 = []
exec_time1 = []
exec_time2 = []
sizeOfArray = 5000
numOfIterations = 200
for i in xrange(numOfIterations):
A = np.random.randint(0,255,(sizeOfArray,sizeOfArray))
B = np.random.randint(0,255,(sizeOfArray,sizeOfArray))
a = time.clock()
res = (A==B).all()
b = time.clock()
exec_time0.append( b - a )
a = time.clock()
res = np.array_equal(A,B)
b = time.clock()
exec_time1.append( b - a )
a = time.clock()
res = np.array_equiv(A,B)
b = time.clock()
exec_time2.append( b - a )
print 'Method: (A==B).all(), ', np.mean(exec_time0)
print 'Method: np.array_equal(A,B),', np.mean(exec_time1)
print 'Method: np.array_equiv(A,B),', np.mean(exec_time2)
산출
Method: (A==B).all(), 0.03031857
Method: np.array_equal(A,B), 0.030025185
Method: np.array_equiv(A,B), 0.030141515
위의 결과에 따르면, numpy 메소드는 == 연산자와 all () 메소드 의 조합보다 빠르며 numpy 메소드를 비교 하면 가장 빠른 것이 numpy.array_equal 메소드 인 것 같습니다 .
두 배열이 동일 할 수 있는지 확인하려면 shape
및 elements
사용한다 np.array_equal
이 문서에서 권장하는 방법으로.
Performance-wise don't expect that any equality check will beat another, as there is not much room to optimize
comparing two elements
. Just for the sake, i still did some tests.
import numpy as np
import timeit
A = np.zeros((300, 300, 3))
B = np.zeros((300, 300, 3))
C = np.ones((300, 300, 3))
timeit.timeit(stmt='(A==B).all()', setup='from __main__ import A, B', number=10**5)
timeit.timeit(stmt='np.array_equal(A, B)', setup='from __main__ import A, B, np', number=10**5)
timeit.timeit(stmt='np.array_equiv(A, B)', setup='from __main__ import A, B, np', number=10**5)
> 51.5094
> 52.555
> 52.761
So pretty much equal, no need to talk about the speed.
The (A==B).all()
behaves pretty much as the following code snippet:
x = [1,2,3]
y = [1,2,3]
print all([x[i]==y[i] for i in range(len(x))])
> True
Usually two arrays will have some small numeric errors,
You can use numpy.allclose(A,B)
, instead of (A==B).all()
. This returns a bool True/False
참고URL : https://stackoverflow.com/questions/10580676/comparing-two-numpy-arrays-for-equality-element-wise
'Programing' 카테고리의 다른 글
Xcode 프로젝트 및 관련 폴더를 복제하고 이름을 바꿉니다. (0) | 2020.05.12 |
---|---|
iOS 원격 디버깅 (0) | 2020.05.12 |
장고 템플릿 변수와 자바 스크립트 (0) | 2020.05.12 |
SQL에서 무작위로 행을 선택하는 방법은 무엇입니까? (0) | 2020.05.11 |
Android 애플리케이션에서 현재 시간 및 날짜 표시 (0) | 2020.05.11 |