- Sparse matrices ( scipy.sparse )#
- Contents#
- Sparse array classes#
- Sparse matrix classes#
- Functions#
- Submodules#
- Exceptions#
- Usage information#
- Matrix vector product#
- Example 1#
- Example 2#
- Further details#
- Разреженные матрицы в Python с помощью Scipy
- Способы создания разреженных матрицы Scipy
- Как создать список координат в Scipy
- Как создать с форматом сжатого хранения строкой (CSS) в Scipy
- Как создать с форматом сжатого хранения столбцом (CSС) в Scipy
Sparse matrices ( scipy.sparse )#
This package is switching to an array interface, compatible with NumPy arrays, from the older matrix interface. We recommend that you use the array objects ( bsr_array , coo_array , etc.) for all new work.
When using the array interface, please note that:
- x * y no longer performs matrix multiplication, but element-wise multiplication (just like with NumPy arrays). To make code work with both arrays and matrices, use x @ y for matrix multiplication.
- Operations such as sum, that used to produce dense matrices, now produce arrays, whose multiplication behavior differs similarly.
- Sparse arrays currently must be two-dimensional. This also means that all slicing operations on these objects must produce two-dimensional results, or they will result in an error. This will be addressed in a future version.
The construction utilities ( eye , kron , random , diags , etc.) have not yet been ported, but their results can be wrapped into arrays:
Contents#
Sparse array classes#
bsr_array (arg1[, shape, dtype, copy, blocksize])
Block Sparse Row format sparse array.
A sparse matrix in COOrdinate format.
Compressed Sparse Column matrix
Compressed Sparse Row matrix
Sparse matrix with DIAgonal storage
Dictionary Of Keys based sparse matrix.
Row-based LIst of Lists sparse matrix
This class provides a base class for all sparse arrays.
Sparse matrix classes#
bsr_matrix (arg1[, shape, dtype, copy, blocksize])
Block Sparse Row format sparse matrix.
A sparse matrix in COOrdinate format.
Compressed Sparse Column matrix
Compressed Sparse Row matrix
Sparse matrix with DIAgonal storage
Dictionary Of Keys based sparse matrix.
Row-based LIst of Lists sparse matrix
This class provides a base class for all sparse matrix classes.
Functions#
Sparse matrix with ones on diagonal
Identity matrix in sparse format
kronecker product of sparse matrices A and B
kronecker sum of sparse matrices A and B
diags (diagonals[, offsets, shape, format, dtype])
Construct a sparse matrix from diagonals.
Return a sparse matrix from diagonals.
Build a block diagonal sparse matrix from provided matrices.
Return the lower triangular portion of a matrix in sparse format
Return the upper triangular portion of a matrix in sparse format
Build a sparse matrix from sparse sub-blocks
Stack sparse matrices horizontally (column wise)
Stack sparse matrices vertically (row wise)
Generate a sparse matrix of the given shape and density with uniformly distributed values.
Generate a sparse matrix of the given shape and density with randomly distributed values.
Save and load sparse matrices:
Save a sparse matrix to a file using .npz format.
Load a sparse matrix from a file using .npz format.
Return the indices and values of the nonzero elements of a matrix
Identifying sparse matrices:
Is x of a sparse array type?
Is x of a sparse matrix type?
Is x of a bsr_matrix type?
Submodules#
Compressed sparse graph routines (scipy.sparse.csgraph)
Sparse linear algebra (scipy.sparse.linalg)
Exceptions#
Usage information#
There are seven available sparse matrix types:
- csc_matrix: Compressed Sparse Column format
- csr_matrix: Compressed Sparse Row format
- bsr_matrix: Block Sparse Row format
- lil_matrix: List of Lists format
- dok_matrix: Dictionary of Keys format
- coo_matrix: COOrdinate format (aka IJV, triplet format)
- dia_matrix: DIAgonal format
To construct a matrix efficiently, use either dok_matrix or lil_matrix. The lil_matrix class supports basic slicing and fancy indexing with a similar syntax to NumPy arrays. As illustrated below, the COO format may also be used to efficiently construct matrices. Despite their similarity to NumPy arrays, it is strongly discouraged to use NumPy functions directly on these matrices because NumPy may not properly convert them for computations, leading to unexpected (and incorrect) results. If you do want to apply a NumPy function to these matrices, first check if SciPy has its own implementation for the given sparse matrix class, or convert the sparse matrix to a NumPy array (e.g., using the toarray() method of the class) first before applying the method.
To perform manipulations such as multiplication or inversion, first convert the matrix to either CSC or CSR format. The lil_matrix format is row-based, so conversion to CSR is efficient, whereas conversion to CSC is less so.
All conversions among the CSR, CSC, and COO formats are efficient, linear-time operations.
Matrix vector product#
To do a vector product between a sparse matrix and a vector simply use the matrix dot method, as described in its docstring:
>>> import numpy as np >>> from scipy.sparse import csr_matrix >>> A = csr_matrix([[1, 2, 0], [0, 0, 3], [4, 0, 5]]) >>> v = np.array([1, 0, -1]) >>> A.dot(v) array([ 1, -3, -1], dtype=int64)
As of NumPy 1.7, np.dot is not aware of sparse matrices, therefore using it will result on unexpected results or errors. The corresponding dense array should be obtained first instead:
>>> np.dot(A.toarray(), v) array([ 1, -3, -1], dtype=int64)
but then all the performance advantages would be lost.
The CSR format is specially suitable for fast matrix vector products.
Example 1#
Construct a 1000×1000 lil_matrix and add some values to it:
>>> from scipy.sparse import lil_matrix >>> from scipy.sparse.linalg import spsolve >>> from numpy.linalg import solve, norm >>> from numpy.random import rand
>>> A = lil_matrix((1000, 1000)) >>> A[0, :100] = rand(100) >>> A[1, 100:200] = A[0, :100] >>> A.setdiag(rand(1000))
Now convert it to CSR format and solve A x = b for x:
>>> A = A.tocsr() >>> b = rand(1000) >>> x = spsolve(A, b)
Convert it to a dense matrix and solve, and check that the result is the same:
Now we can compute norm of the error with:
>>> err = norm(x-x_) >>> err 1e-10 True
Example 2#
Construct a matrix in COO format:
>>> from scipy import sparse >>> from numpy import array >>> I = array([0,3,1,0]) >>> J = array([0,3,1,2]) >>> V = array([4,5,7,9]) >>> A = sparse.coo_matrix((V,(I,J)),shape=(4,4))
Notice that the indices do not need to be sorted.
Duplicate (i,j) entries are summed when converting to CSR or CSC.
>>> I = array([0,0,1,3,1,0,0]) >>> J = array([0,2,1,3,1,0,0]) >>> V = array([1,1,1,1,1,1,1]) >>> B = sparse.coo_matrix((V,(I,J)),shape=(4,4)).tocsr()
This is useful for constructing finite-element stiffness and mass matrices.
Further details#
CSR column indices are not necessarily sorted. Likewise for CSC row indices. Use the .sorted_indices() and .sort_indices() methods when sorted indices are required (e.g., when passing data to other libraries).
Compressed sparse graph routines ( scipy.sparse.csgraph )
© Copyright 2008-2023, The SciPy community.
Разреженные матрицы в Python с помощью Scipy
В предыдущей статье мы говорили о том, как можно представлять разреженные матрицы. Сегодня рассмотрим их создание с примерами кода на Python с помощью библиотеки Scipy. Читайте в этой статье: как можно создать разреженные матрицы в Python, как создаются матрицы формата списка координат (COOrdinate list), сжатого хранения столбцом (Compresed Sparse Row) и строкой (Compresed Sparse Column).
Способы создания разреженных матрицы Scipy
Самый простой формат представления разреженных матриц – это список координат (COOrdinate list, COO). Согласному этому представлению компьютер хранит массивы строк и столбцов ненулевых значений, а также сами ненулевые значения.
В Scipy разреженные матрицы создаются с помощью модуля sparse , который имеет соответствующие форматы. Их можно создать несколькими способами, передав в качестве аргументов:
- плотную матрицу,
- другую разреженную матрцу,
- форму матрицы (вернется пустая матрица)
- массивы с индексами строк и столбцов и сами значенния.
Разреженные матрицы Scipy имеют полезные методы для конвертации в плотные ( todense или toarray ), сжатые строкой ( tocsr ) и сжатые столбцом ( tocsc ).
Как создать список координат в Scipy
Создадим разреженную матрицу на основе плотной матрицы из предыдущей статьи. Пример кода на Python того, как создаются разреженные матрицы Scipy:
import numpy as np import scipy.sparse as sparse arr = np.array([ [0, 1, 0, 0, 0, 0, 0], [0, 0, 2, 1, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 3, 0], ]) print(sparse.coo_matrix(arr)) # Результат: (0, 1) 1 (1, 2) 2 (1, 3) 1 (1, 6) 1 (3, 3) 1 (3, 5) 3
Как видите, результат тот же, что мы проделывали вручную. Первым элементом вернувшегося массива является индекс строки, вторым – индекс столбца, а справа – ненулевые значения, соответствующим этим индексам.
Мы могли бы также передать массивы индексов строк и столбцов с ненулевыми значениями. Вот так это выглядит в Python:
import numpy as np import scipy.sparse as sparse rows = [0, 1, 1, 1, 3 ,3] cols = [1, 2, 3, 6, 3, 5] data = [1, 2, 1, 1, 1, 3] coo = sparse.coo_matrix((data, (rows, cols))) # Результат тот же, что и выше
Преимущества списка координат:
- обеспечивает быстрое преобразование между разреженными форматами, например, CSR и CSC;
- разрешает повторяющиеся индексы, поэтому легко изменять форму.
Недостатки списка координат:
Как создать с форматом сжатого хранения строкой (CSS) в Scipy
Сжатое хранение строкой (Compressed Sparse Row, CSR) подразумевает подсчет кумулятивной суммы количества элементов в строке вместо индексов строк.
В Python-библиотеке Scipy для создания разреженных матриц с сжатым хранением строкой используется функция csr_matrix :
# `arr' тот же, что и выше csr = sparse.csr_matrix(arr) print(csr) # Результат: (0, 1) 1 (1, 2) 2 (1, 3) 1 (1, 6) 1 (3, 3) 1 (3, 5) 3
Разреженные матрицы данного формата поддерживают арифметические операции: сложение, вычитание, умножение, деление и возведение в степень.
Преимущества сжатого хранения строкой:
- эффективные операции с матрицами такого же формата (CSR + CSR, CSR * CSR и т.д.);
- эффективное извлечение строк;
- быстрое умножение матриц.
Недостатки сжатого хранения строкой:
- медленное извлечение столбцов;
- медленное преобразование в форматы список списков (LIL) и словарь ключей (DOK).
Как создать с форматом сжатого хранения столбцом (CSС) в Scipy
Сжатое хранение столбцом (Compressed Sparse Column, CSС) подразумевает подсчет кумулятивной суммы количества элементов в столбце. В машинном обучении (machine learning) CSС-матрицы наиболее распространены, так как часто приходится работать с набором признаков, которые как раз и составляют столбцы.
В Python-библиотеке Scipy для создания разреженных матриц с сжатым хранением столбцом используется функция csc_matrix :
csc = sparse.csc_matrix(arr) print(csc) # Результат: (0, 1) 1 (1, 2) 2 (1, 3) 1 (3, 3) 1 (3, 5) 3 (1, 6) 1
Обратите внимание, что последними элементами идет 3, а затем 1, поскольку подсчет происходит по столбам, а столбец с со значением 3 встречается раньше значения 1.
Преимущества и недостатки такие же, как у CSR, но только вместо строк используются столбцы.
Больше подробностей о работе с разреженными матрицами в Python для решения задач Data Science вы узнаете на специализированном курсе по машинному обучению «PYML: Введение в машинное обучение на Python» в лицензированном учебном центре обучения и повышения квалификации разработчиков, менеджеров, архитекторов, инженеров, администраторов, Data Scientist’ов и аналитиков Big Data в Москве.