Как преобразовать numpy.matrix или массив в скудную разреженную матрицу
Для разреженной матрицы SciPy можно использовать todense()
или же toarray()
преобразовать в матрицу или массив NumPy. Какие функции делать обратное?
Я искал, но не знал, какие ключевые слова должны быть правильными.
3 ответа
Вы можете передать пустой массив или матрицу в качестве аргумента при инициализации разреженной матрицы. Например, для матрицы 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]) блочная матрица разреженных строк
coo_matrix(arg1[, shape, dtype, copy]) Разреженная матрица в формате COOrdinate.
csc_matrix (arg1 [, shape, dtype, copy]) Сжатая матрица разреженных столбцов
csr_matrix(arg1[, shape, dtype, copy]) Сжатая матрица разреженных строк
dia_matrix(arg1[, shape, dtype, copy]) Разреженная матрица с DIAgonal хранилищем
dok_matrix(arg1[, shape, dtype, copy]) Разреженная матрица словаря ключей.
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
В Python библиотеку Scipy можно использовать для преобразования двумерной матрицы NumPy в разреженную матрицу. Пакет SciPy 2-D разреженной матрицы для числовых данных - scipy.sparse
Пакет scipy.sparse предоставляет различные классы для создания следующих типов разреженных матриц из 2-мерной матрицы:
- Блокировать матрицу разреженных строк
- Разреженная матрица в формате COOrdinate.
- Сжатая матрица разреженных столбцов
- Сжатая матрица разреженных строк
- Разреженная матрица с DIAgonal хранилищем
- Dictionary Of Keys based sparse matrix.
- Row-based list of lists sparse matrix
- This class provides a base class for all sparse matrices.
CSR (Compressed Sparse Row) or CSC (Compressed Sparse Column) formats support efficient access and matrix operations.
Example code to Convert Numpy matrix into Compressed Sparse Column(CSC) matrix & Compressed Sparse Row (CSR) matrix using Scipy classes:
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
create a 2-D Numpy matrix
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))
Print the matrix & other details:
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'>
Converting Matrix A to the Compressed sparse row matrix representation using csr_matrix Class:
S = csr_matrix(A)
print("Sparse 'row' matrix: \n",S)
print("Memory utilised (bytes): ", sys.getsizeof(S))
print("Type of the object", type(S))
The output of print statements:
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'>
Converting Matrix A to Compressed Sparse Column matrix representation using csc_matrix Class:
S = csc_matrix(A)
print("Sparse 'column' matrix: \n",S)
print("Memory utilised (bytes): ", sys.getsizeof(S))
print("Type of the object", type(S))
The output of print statements:
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/
Что касается обратного, функция inv(A)
, но я не буду рекомендовать его использовать, поскольку для больших матриц это очень затратно в вычислительном отношении и нестабильно. Вместо этого вы должны использовать приближение к обратному, или, если вы хотите решить Ax = b, вам не нужен A-1.