numpy.matrix 또는 배열을 scipy 희소 행렬로 변환하는 방법


86

SciPy 희소 행렬의 경우 todense()또는 toarray()을 사용 하여 NumPy 행렬 또는 배열로 변환 할 수 있습니다 . 역을 수행하는 기능은 무엇입니까?

검색했지만 어떤 키워드가 적합한 지 알 수 없었습니다.

답변:


127

희소 행렬을 초기화 할 때 numpy 배열 또는 행렬을 인수로 전달할 수 있습니다. 예를 들어 CSR 매트릭스의 경우 다음을 수행 할 수 있습니다.

>>> import numpy as np
>>> from scipy import sparse
>>> A = np.array([[1,2,0],[0,0,3],[1,0,4]])
>>> B = np.matrix([[1,2,0],[0,0,3],[1,0,4]])

>>> A
array([[1, 2, 0],
       [0, 0, 3],
       [1, 0, 4]])

>>> sA = sparse.csr_matrix(A)   # Here's the initialization of the sparse matrix.
>>> sB = sparse.csr_matrix(B)

>>> sA
<3x3 sparse matrix of type '<type 'numpy.int32'>'
        with 5 stored elements in Compressed Sparse Row format>

>>> print sA
  (0, 0)        1
  (0, 1)        2
  (1, 2)        3
  (2, 0)        1
  (2, 2)        4

2
고차원 배열은 어떻습니까?
Nirmal

매트릭스에 대한 메모리 오류가 발생합니다 (~ 25,000x25,000). 내가 적용 할 때 또한, 메모리 소비는 미친 듯이 점프sparse.csr_matrix
마틴 토마스

23

scipy에는 여러 희소 행렬 클래스가 있습니다.

bsr_matrix (arg1 [, shape, dtype, copy, blocksize]) Block Sparse Row 행렬
coo_matrix (arg1 [, shape, dtype, copy]) COOrdinate 형식의 희소 행렬입니다.
csc_matrix (arg1 [, shape, dtype, copy]) Compressed Sparse Column matrix
csr_matrix (arg1 [, shape, dtype, copy]) Compressed Sparse Row matrix
dia_matrix (arg1 [, shape, dtype, copy]) Sparse matrix with DIAgonal storage
dok_matrix (arg1 [, shape, dtype, copy]) Dictionary Of Keys 기반 희소 행렬.
lil_matrix (arg1 [, shape, dtype, copy]) 행 기반 연결 목록 희소 행렬

그들 중 누구라도 변환을 할 수 있습니다.

import numpy as np
from scipy import sparse
a=np.array([[1,0,1],[0,0,1]])
b=sparse.csr_matrix(a)
print(b)

(0, 0)  1
(0, 2)  1
(1, 2)  1

http://docs.scipy.org/doc/scipy/reference/sparse.html#usage-information을 참조하세요 .


0

역의 경우 함수는 inv(A)이지만 거대한 행렬의 경우 계산 비용이 많이 들고 불안정하기 때문에 사용하지 않는 것이 좋습니다. 대신, 역에 대한 근사치를 사용해야합니다. 또는 Ax = b를 풀고 싶다면 A -1 이 필요하지 않습니다 .


4
질문은 행렬 연산으로 역이 아닌 numpy 행렬 / 배열을 사용하여 scipy 희소 행렬을 생성하는 방법을 묻습니다.
Virgil Ming

0

Python에서는 Scipy 라이브러리 를 사용하여 2D NumPy 행렬을 Sparse 행렬로 변환 할 수 있습니다. 숫자 데이터 용 SciPy 2D 희소 행렬 패키지는 scipy.sparse입니다.

scipy.sparse 패키지는 2 차원 행렬 에서 다음과 같은 유형의 Sparse 행렬 을 만들기 위해 다양한 클래스를 제공합니다 .

  1. 블록 희소 행 행렬
  2. COOrdinate 형식의 희소 행렬입니다.
  3. 압축 된 희소 열 행렬
  4. 압축 된 희소 행 행렬
  5. DIAgonal 스토리지가있는 희소 행렬
  6. 키 사전 기반 희소 행렬.
  7. 행 기반 목록 희소 행렬
  8. 이 클래스는 모든 희소 행렬에 대한 기본 클래스를 제공합니다.

CSR (Compressed Sparse Row) 또는 CSC (Compressed Sparse Column) 형식은 효율적인 액세스 및 매트릭스 작업을 지원합니다.

Scipy 클래스를 사용하여 Numpy 행렬을 CSC (Compressed Sparse Column) 행렬 및 CSR (Compressed Sparse Row) 행렬로 변환하는 예제 코드 :

import sys                 # Return the size of an object in bytes
import numpy as np         # To create 2 dimentional matrix
from scipy.sparse import csr_matrix, csc_matrix 
# csr_matrix: used to create compressed sparse row matrix from Matrix
# csc_matrix: used to create compressed sparse column matrix from Matrix

2 차원 Numpy 행렬 만들기

A = np.array([[1, 0, 0, 0, 0, 0],\
              [0, 0, 2, 0, 0, 1],\
              [0, 0, 0, 2, 0, 0]])
print("Dense matrix representation: \n", A)
print("Memory utilised (bytes): ", sys.getsizeof(A))
print("Type of the object", type(A))

매트릭스 및 기타 세부 정보를 인쇄합니다.

Dense matrix representation: 
 [[1 0 0 0 0 0]
 [0 0 2 0 0 1]
 [0 0 0 2 0 0]]
Memory utilised (bytes):  184
Type of the object <class 'numpy.ndarray'>

csr_matrix 클래스를 사용하여 행렬 A를 압축 된 희소 행 행렬 표현으로 변환 :

S = csr_matrix(A)
print("Sparse 'row' matrix: \n",S)
print("Memory utilised (bytes): ", sys.getsizeof(S))
print("Type of the object", type(S))

print 문의 출력 :

Sparse 'row' matrix:
(0, 0) 1
(1, 2) 2
(1, 5) 1
(2, 3) 2
Memory utilised (bytes): 56
Type of the object: <class 'scipy.sparse.csr.csc_matrix'>

csc_matrix 클래스를 사용하여 행렬 A를 압축 된 희소 열 행렬 표현으로 변환 :

S = csc_matrix(A)
print("Sparse 'column' matrix: \n",S)
print("Memory utilised (bytes): ", sys.getsizeof(S))
print("Type of the object", type(S))

print 문의 출력 :

Sparse 'column' matrix:
(0, 0) 1
(1, 2) 2
(2, 3) 2
(1, 5) 1
Memory utilised (bytes): 56
Type of the object: <class 'scipy.sparse.csc.csc_matrix'>

알 수 있듯이 압축 된 행렬의 크기는 56 바이트이고 원래의 행렬 크기는 184 바이트입니다.

자세한 설명과 코드 예제는 https://limitlessdatascience.wordpress.com/2020/11/26/sparse-matrix-in-machine-learning/ 문서를 참조하십시오.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.