坐标格式的稀疏矩阵。
也被称为“ijv”或“三重”格式。
这可以通过几种方式实例化:
coo_matrix(D)
密集矩阵D;
coo_matrix(S)
与另一个稀疏矩阵S(等价于S.tocoo())
coo_matrix((M, N), [dtype])
构造一个形状为(M, N)的空矩阵
coo_matrix((data, (i, j)), [shape=(M, N)])
从三个数组构造:
1. data[:] the entries of the matrix, in any order 矩阵的元素,以任何顺序
2. i[:] the row indices of the matrix entries 矩阵项的行下标
3. j[:] the column indices of the matrix entries 矩阵项的列下标
参数:
- dtype : dtype
- Data type of the matrix
- shape : 2-tuple
- Shape of the matrix
- ndim : int
- Number of dimensions (this is always 2)
- nnz
- Number of stored values, including explicit zeros
- data
- COO format data array of the matrix
- row
- COO format row index array of the matrix
- col
- COO format column index array of the matrix
稀疏矩阵可以用于算术运算:它们支持加,减,乘,除,矩阵幂。
COO格式优势
方便稀疏格式之间的快速转换;
允许重复条目(见示例)
非常快速的转换CSR/CSC格式
- >>> from scipy.sparse import coo_matrix
- >>> import numpy as np
- >>> coo_matrix((3, 4), dtype=np.int8).toarray()
- array([[0, 0, 0, 0],
- [0, 0, 0, 0],
- [0, 0, 0, 0]], dtype=int8)
- >>> # Constructing a matrix using ijv format
- >>> row = np.array([0, 3, 1, 0])
- >>> col = np.array([0, 3, 1, 2])
- >>> data = np.array([4, 5, 7, 9])
- >>> coo_matrix((data, (row, col)), shape=(4, 4)).toarray()
- array([[4, 0, 9, 0],
- [0, 7, 0, 0],
- [0, 0, 0, 0],
- [0, 0, 0, 5]])
- >>> # Constructing a matrix with duplicate indices
- >>> row = np.array([0, 0, 1, 3, 1, 0, 0])
- >>> col = np.array([0, 2, 1, 3, 1, 0, 0])
- >>> data = np.array([1, 1, 1, 1, 1, 1, 1])
- >>> coo = coo_matrix((data, (row, col)), shape=(4, 4))
- >>> coo = coo_matrix((data, (row, col)), shape=(4, 4))
- >>> coo.toarray()
- array([[3, 0, 1, 0],
- [0, 2, 0, 0],
- [0, 0, 0, 0],
- [0, 0, 0, 1]])
- >>> #保持重复索引,直到隐式或显式求和
eye(N, M=None, k=0, dtype=float) 是scipy包中的一个创建特殊矩阵(单位矩阵E)的方法
- >>> from scipy import *
-
- >>> eye(3)
- [[1. 0. 0.]
- [0. 1. 0.]
- [0. 0. 1.]]
- >>> eye(3,3)
- array([[1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.]])
- >>> eye(3,4)
- array([[1., 0., 0., 0.],
- [0., 1., 0., 0.],
- [0., 0., 1., 0.]])
- >>> eye(3,4,1)
- array([[0., 1., 0., 0.],
- [0., 0., 1., 0.],
- [0., 0., 0., 1.]])
- >>> eye(3,4,2)
- array([[0., 0., 1., 0.],
- [0., 0., 0., 1.],
- [0., 0., 0., 0.]])