Sparse matrix to normal matrix python
I have a Sqlite database that contains following type of schema: Show
This table contains terms with their respective counts in the document. like
This matrix can be considered as sparse matrix as each documents contains very few terms that will have a non-zero value. How would I create a dense matrix from this sparse matrix using numpy as I have to calculate the similarity among documents using cosine similarity. This dense matrix will look like a table that have docid as the first column and all the terms will be listed as the first row.and remaining cells will contain counts. Return a dense matrix representation of this matrix. Parametersorder{‘C’, ‘F’}, optionalWhether to store multi-dimensional data in C (row-major) or Fortran (column-major) order in memory. The default is ‘None’, which provides no ordering guarantees. Cannot be specified in conjunction with the out argument. outndarray, 2-D, optionalIf specified, uses this array (or
A NumPy matrix object with the same shape and containing the same
data represented by the sparse matrix, with the requested memory order. If out was passed and was an array (rather than a SciPy 2-D sparse array package for numeric data. Note 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
( When using the array interface, please note that:
The construction utilities ( Contents#Sparse array classes#
Sparse matrix classes#
Functions#Building sparse matrices:
Save and load sparse matrices:
Sparse matrix tools:
Identifying sparse matrices:
Submodules#
Exceptions#
Usage information#There are seven available sparse matrix types:
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) Warning 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 1000x1000 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: >>> x_ = solve(A.toarray(), b) Now we can compute norm of the error with: >>> err = norm(x-x_) >>> err < 1e-10 True It should be small :) 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). How do you convert a sparse matrix to a general matrix?As a general criterion the number of non-zero elements are expected to be equal to the number of rows or number of columns. To convert a sparse matrix into a matrix R, we can use as. matrix function with the sparse matrix object name.
How do you convert sparse to matrix in python?Sparse Matrices in Python
A dense matrix stored in a NumPy array can be converted into a sparse matrix using the CSR representation by calling the csr_matrix() function.
How do you convert a sparse matrix into a dense matrix in python?1 Answer. You can use either todense() or toarray() function to convert a CSR matrix to a dense matrix.
What is Toarray () python?toarray returns an ndarray; todense returns a matrix. If you want a matrix, use todense ; otherwise, use toarray .
|