scipy.sparse.

csr_matrix#

class scipy.sparse.csr_matrix(arg1, shape=None, dtype=None, copy=False, *, maxprint=None)[源]#

压缩稀疏行矩阵。

这可以通过以下几种方式实例化:
csr_matrix(D)

其中 D 是一个二维 ndarray

csr_matrix(S)

与另一个稀疏数组或矩阵 S(等同于 S.tocsr())

csr_matrix((M, N), [dtype])

用于构造形状为 (M, N) 的空矩阵,dtype 是可选的,默认为 dtype='d'。

csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)])

其中 datarow_indcol_ind 满足关系 a[row_ind[k], col_ind[k]] = data[k]

csr_matrix((data, indices, indptr), [shape=(M, N)])

是标准的 CSR 表示,其中行 i 的列索引存储在 indices[indptr[i]:indptr[i+1]] 中,其对应值存储在 data[indptr[i]:indptr[i+1]] 中。如果未提供 shape 参数,则矩阵维度将从索引数组中推断。

属性:
dtypedtype

矩阵的数据类型

shape2元组

矩阵的形状

ndimint

维度数(始终为 2)

nnz

存储值的数量,包括显式零。

size

存储值的数量。

data

矩阵的 CSR 格式数据数组

indices

矩阵的 CSR 格式索引数组

indptr

矩阵的 CSR 格式索引指针数组

has_sorted_indices

索引是否已排序

has_canonical_format

数组/矩阵是否具有已排序的索引且无重复项

T

转置。

方法

__len__()

__mul__(other)

arcsin()

逐元素的 arcsin。

arcsinh()

逐元素的 arcsinh。

arctan()

逐元素的 arctan。

arctanh()

逐元素的 arctanh。

argmax([axis, out, explicit])

返回沿轴的最大元素的索引。

argmin([axis, out, explicit])

返回沿轴的最小元素的索引。

asformat(format[, copy])

以传入的格式返回此数组/矩阵。

asfptype()

将矩阵上转换为浮点格式(如果必要)

astype(dtype[, casting, copy])

将数组/矩阵元素转换为指定类型。

ceil()

逐元素的 ceil。

check_format([full_check])

检查数组/矩阵是否符合 CSR 或 CSC 格式。

conj([copy])

逐元素的复共轭。

conjugate([copy])

逐元素的复共轭。

copy()

返回此数组/矩阵的副本。

count_nonzero([axis])

非零条目数,等同于

deg2rad()

逐元素的 deg2rad。

diagonal([k])

返回数组/矩阵的第 k 条对角线。

dot(other)

普通点积

eliminate_zeros()

从数组/矩阵中移除零条目

expm1()

逐元素的 expm1。

floor()

逐元素的 floor。

getH()

返回此矩阵的 Hermitian 转置。

get_shape()

获取矩阵的形状

getcol(j)

返回矩阵第 j 列的副本,作为一个 (m x 1) 稀疏矩阵(列向量)。

getformat()

矩阵存储格式

getmaxprint()

打印时显示的最大元素数量。

getnnz([axis])

存储值的数量,包括显式零。

getrow(i)

返回矩阵第 i 行的副本,作为一个 (1 x n) 稀疏矩阵(行向量)。

log1p()

逐元素的 log1p。

max([axis, out, explicit])

返回数组/矩阵的最大值或沿轴的最大值。

maximum(other)

此数组/矩阵与另一个数组/矩阵之间的逐元素最大值。

mean([axis, dtype, out])

计算沿指定轴的算术平均值。

min([axis, out, explicit])

返回数组/矩阵的最小值或沿轴的最大值。

minimum(other)

此数组/矩阵与另一个数组/矩阵之间的逐元素最小值。

multiply(other)

与另一个数组/矩阵进行逐元素乘法。

nanmax([axis, out, explicit])

返回沿轴的最大值,忽略任何 NaN。

nanmin([axis, out, explicit])

返回沿轴的最小值,忽略任何 NaN。

nonzero()

数组/矩阵的非零索引。

power(n[, dtype])

此函数执行逐元素幂运算。

prune()

移除所有非零元素后的空白空间。

rad2deg()

逐元素的 rad2deg。

reshape(self, shape[, order, copy])

在不更改数据的情况下,为稀疏数组/矩阵赋予新形状。

resize(*shape)

将数组/矩阵就地调整大小到由 shape 给出的维度。

rint()

逐元素的 rint。

set_shape(shape)

就地设置矩阵的形状

setdiag(values[, k])

设置数组/矩阵的对角线或非对角线元素。

sign()

逐元素的 sign。

sin()

逐元素的 sin。

sinh()

逐元素的 sinh。

sort_indices()

对此数组/矩阵的索引进行*就地*排序

sorted_indices()

返回带有排序索引的此数组/矩阵的副本

sqrt()

逐元素的 sqrt。

sum([axis, dtype, out])

沿着给定轴对数组/矩阵元素求和。

sum_duplicates()

通过将重复条目相加来消除它们

tan()

逐元素的 tan。

tanh()

逐元素的 tanh。

toarray([order, out])

返回此稀疏数组/矩阵的密集 ndarray 表示。

tobsr([blocksize, copy])

将此数组/矩阵转换为分块稀疏行(Block Sparse Row)格式。

tocoo([copy])

将此数组/矩阵转换为 COOrdinate 格式。

tocsc([copy])

将此数组/矩阵转换为压缩稀疏列(Compressed Sparse Column)格式。

tocsr([copy])

将此数组/矩阵转换为压缩稀疏行(Compressed Sparse Row)格式。

todense([order, out])

返回此稀疏矩阵的密集表示。

todia([copy])

将此数组/矩阵转换为稀疏对角(DIAgonal)格式。

todok([copy])

将此数组/矩阵转换为键字典(Dictionary Of Keys)格式。

tolil([copy])

将此数组/矩阵转换为列表之列表(List of Lists)格式。

trace([offset])

返回稀疏数组/矩阵沿对角线的和。

transpose([axes, copy])

反转稀疏数组/矩阵的维度。

trunc()

逐元素的 trunc。

__getitem__

注意

稀疏矩阵可用于算术运算:它们支持加法、减法、乘法、除法和矩阵幂。

CSR 格式的优点
  • 高效的算术运算,如 CSR + CSR, CSR * CSR 等。

  • 高效的行切片

  • 快速矩阵向量乘积

CSR 格式的缺点
  • 慢速列切片操作(考虑使用 CSC)

  • 稀疏结构更改成本高(考虑使用 LIL 或 DOK)

规范格式
  • 在每行中,索引按列排序。

  • 没有重复条目。

示例

>>> import numpy as np
>>> from scipy.sparse import csr_matrix
>>> csr_matrix((3, 4), dtype=np.int8).toarray()
array([[0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0]], dtype=int8)
>>> row = np.array([0, 0, 1, 2, 2, 2])
>>> col = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> csr_matrix((data, (row, col)), shape=(3, 3)).toarray()
array([[1, 0, 2],
       [0, 0, 3],
       [4, 5, 6]])
>>> indptr = np.array([0, 2, 3, 6])
>>> indices = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> csr_matrix((data, indices, indptr), shape=(3, 3)).toarray()
array([[1, 0, 2],
       [0, 0, 3],
       [4, 5, 6]])

重复条目会被求和

>>> row = np.array([0, 1, 2, 0])
>>> col = np.array([0, 1, 1, 0])
>>> data = np.array([1, 2, 4, 8])
>>> csr_matrix((data, (row, col)), shape=(3, 3)).toarray()
array([[9, 0, 0],
       [0, 2, 0],
       [0, 4, 0]])

作为增量构建 CSR 矩阵的示例,以下代码片段从文本构建一个词项-文档矩阵

>>> docs = [["hello", "world", "hello"], ["goodbye", "cruel", "world"]]
>>> indptr = [0]
>>> indices = []
>>> data = []
>>> vocabulary = {}
>>> for d in docs:
...     for term in d:
...         index = vocabulary.setdefault(term, len(vocabulary))
...         indices.append(index)
...         data.append(1)
...     indptr.append(len(indices))
...
>>> csr_matrix((data, indices, indptr), dtype=int).toarray()
array([[2, 1, 0, 0],
       [0, 1, 1, 1]])