2013-01-24 3 views
8

논리 연산 (주로 요소 별 OR)을 수행하는 데 필요한 부울 값으로 채워진 스파 스 행렬 집합이 있습니다. NumPy와 같이 scipy.sparse 행렬의 부울 연산

는 DTYPE = 'BOOL'와 행렬들을 합산하여 준다 소자 현명하지만 심한 부작용있어, OR :

>>> from scipy import sparse 
>>> [a,b] = [sparse.rand(5,5,density=0.1,format='lil').astype('bool') 
... for x in range(2)] 
>>> b 
<5x5 sparse matrix of type '<class 'numpy.bool_'>' 
    with 2 stored elements in LInked List format> 
>>> a+b 
<5x5 sparse matrix of type '<class 'numpy.int8'>' 
    with 4 stored elements in Compressed Sparse Row format> 

데이터 타입이 'INT8'로 변경 얻는다 원인 미래의 운영을위한 문제. 이 말에 의해 주위에받은 수 :

(a+b).astype('bool') 

하지만이 모든 유형의 변화가 성능 저하를 야기 인상을 얻을.

결과의 dtype이 피연산자와 다른 이유는 무엇입니까?
파이썬에서 희소 행렬에 대한 논리 연산을 수행하는 더 좋은 방법이 있습니까?

답변

5

논리 연산은 스파 스 행렬에서는 지원되지 않지만 'bool'로의 변환은 그다지 비싸지 않습니다. 사실, LIL 형식의 행렬을 사용하는 경우, 변환으로 인해 성능 변동에 부정적인 시간이 걸릴 나타날 수 있습니다

a = scipy.sparse.rand(10000, 10000, density=0.001, format='lil').astype('bool') 
b = scipy.sparse.rand(10000, 10000, density=0.001, format='lil').astype('bool') 

In [2]: %timeit a+b 
10 loops, best of 3: 61.2 ms per loop 

In [3]: %timeit (a+b).astype('bool') 
10 loops, best of 3: 60.4 ms per loop 
당신은 그들을 함께 추가하기 전에 LIL 행렬은 CSR 형식으로 변환 한 것으로 나타났습니다 수

가 반환 볼을 체재. 당신이 이미 시작하는 CSR 형식을 사용했던 경우, 변환 오버 헤드가 더 두드러진다 :

In [14]: %timeit a+b 
100 loops, best of 3: 2.28 ms per loop 

In [15]: %timeit (a+b).astype(bool) 
100 loops, best of 3: 2.96 ms per loop 

CSR (및 CSC) 행렬이 실제 비제 항목을 유지하는 1D 배열 인 data 속성이 스파 스 매트릭스의 재 배열 비용은 크기가 아닌 매트릭스의 0이 아닌 항목 수에 따라 달라지며 그 크기는 다릅니다.

a = scipy.sparse.rand(10000, 10000, density=0.0005, format='csr').astype('int8') 
b = scipy.sparse.rand(1000, 1000, density=0.5, format='csr').astype('int8') 

In [4]: %timeit a.astype('bool') # a is 10,000x10,000 with 50,000 non-zero entries 
10000 loops, best of 3: 93.3 us per loop 

In [5]: %timeit b.astype('bool') # b is 1,000x1,000 with 500,000 non-zero entries 
1000 loops, best of 3: 1.7 ms per loop 
관련 문제