numpy.matrix 또는 배열을 scipy 희소 행렬로 변환하는 방법
SciPy 희소 행렬의 경우 todense()
또는 toarray()
을 사용 하여 NumPy 행렬 또는 배열로 변환 할 수 있습니다 . 역을 수행하는 기능은 무엇입니까?
검색했지만 어떤 키워드가 적합한 지 알 수 없었습니다.
희소 행렬을 초기화 할 때 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
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을 참조하세요 .
역의 경우 함수는 inv(A)
이지만 거대한 행렬의 경우 계산 비용이 많이 들고 불안정하기 때문에 사용하지 않는 것이 좋습니다. 대신, 역에 대한 근사치를 사용해야합니다. 또는 Ax = b를 풀고 싶다면 A -1 이 필요하지 않습니다 .
'developer tip' 카테고리의 다른 글
MySQL CASE는 어떻게 작동합니까? (0) | 2020.11.24 |
---|---|
에라토스테네스의 체-소수 찾기 파이썬 (0) | 2020.11.24 |
PDO PHP에서 쿼리 오류를 보는 방법 (0) | 2020.11.24 |
두 목록을 C #의 사전에 매핑 (0) | 2020.11.23 |
$ .ajax (serialize () + extra data)를 통해 데이터를 추가하는 방법 (0) | 2020.11.23 |