SciPy 1.12 中文文档(三十六)
scipy.sparse.dia_matrix
class scipy.sparse.dia_matrix(arg1, shape=None, dtype=None, copy=False)
使用 DIAgonal 存储的稀疏矩阵。
这可以通过几种方式来实例化:
dia_matrix(D)
其中 D 是一个二维 ndarray
dia_matrix(S)
与另一个稀疏数组或矩阵 S 一起(相当于 S.todia())
dia_matrix((M, N), [dtype])
用形状为(M,N)的空矩阵构造,数据类型是可选的,默认为 dtype=’d’。
dia_matrix((data, offsets), shape=(M, N))
其中data[k,:]存储对角线offsets[k]的对角线条目(参见下面的示例)
注意事项
稀疏矩阵可用于算术运算:它们支持加法、减法、乘法、除法和矩阵幂。
示例
>>> import numpy as np
>>> from scipy.sparse import dia_matrix
>>> dia_matrix((3, 4), dtype=np.int8).toarray()
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int8)
>>> data = np.array([[1, 2, 3, 4]]).repeat(3, axis=0)
>>> offsets = np.array([0, -1, 2])
>>> dia_matrix((data, offsets), shape=(4, 4)).toarray()
array([[1, 0, 3, 0],
[1, 2, 0, 4],
[0, 2, 3, 0],
[0, 0, 3, 4]])
>>> from scipy.sparse import dia_matrix
>>> n = 10
>>> ex = np.ones(n)
>>> data = np.array([ex, 2 * ex, ex])
>>> offsets = np.array([-1, 0, 1])
>>> dia_matrix((data, offsets), shape=(n, n)).toarray()
array([[2., 1., 0., ..., 0., 0., 0.],
[1., 2., 1., ..., 0., 0., 0.],
[0., 1., 2., ..., 0., 0., 0.],
...,
[0., 0., 0., ..., 2., 1., 0.],
[0., 0., 0., ..., 1., 2., 1.],
[0., 0., 0., ..., 0., 1., 2.]])
属性:
数据类型dtype
矩阵的数据类型
shape2 元组
矩阵的形状
维数整数
维度数(始终为 2)
存储的值数量,包括显式零。
存储值的数量。
数据
矩阵的 DIA 格式数据数组
偏移量
矩阵的 DIA 格式偏移数组
转置。
方法
__len__() | ||
|---|---|---|
__mul__ | ||
arcsin() | 逐元素反正弦。 | |
arcsinh() | 逐元素反双曲正弦。 | |
arctan() | 逐元素反正切。 | |
arctanh() | 逐元素反双曲正切。 | |
asformat(format[, copy]) | 以传递的格式返回此数组/矩阵。 | |
asfptype() | 将矩阵升级为浮点格式(如有必要) | |
astype(dtype[, casting, copy]) | 将数组/矩阵元素转换为指定类型。 | |
ceil() | 按元素进行向上取整。 | |
conj([copy]) | 对每个元素进行复数共轭。 | |
conjugate([copy]) | 对每个元素进行复数共轭。 | |
copy() | 返回此数组/矩阵的副本。 | |
count_nonzero() | 非零条目的数量,等同于。 | |
deg2rad() | 按元素进行角度转弧度。 | |
diagonal([k]) | 返回数组/矩阵的第 k 条对角线。 | |
dot(other) | 普通点积。 | |
expm1() | 按元素进行 expm1 计算。 | |
floor() | 按元素进行向下取整。 | |
getH() | 返回该矩阵的共轭转置。 | |
get_shape() | 获取矩阵的形状。 | |
getcol(j) | 返回矩阵第 j 列的复制,作为一个 (m x 1) 稀疏矩阵(列向量)。 | |
getformat() | 矩阵存储格式。 | |
getmaxprint() | 打印时显示的最大元素数量。 | |
getnnz([axis]) | 存储值的数量,包括显式的零值。 | |
getrow(i) | 返回矩阵第 i 行的复制,作为 (1 x n) 稀疏矩阵(行向量)。 | |
log1p() | 按元素进行 log1p 计算。 | |
maximum(other) | 数组/矩阵的逐元素最大值。 | |
mean([axis, dtype, out]) | 沿指定轴计算数组/矩阵的算术平均值。 | |
minimum(other) | 数组/矩阵的逐元素最小值。 | |
multiply(other) | 逐点乘以另一个数组/矩阵。 | |
nonzero() | 数组/矩阵的非零索引。 | |
power(n[, dtype]) | 对数组/矩阵进行逐元素的幂运算。 | |
rad2deg() | 逐元素的弧度转角度。 | |
reshape(self, shape[, order, copy]) | 在不改变数据的情况下为稀疏数组/矩阵提供新的形状。 | |
resize(*shape) | 就地调整数组/矩阵的尺寸为给定的shape。 | |
rint() | 逐元素的四舍五入。 | |
set_shape(shape) | 将矩阵的形状就地设置。 | |
setdiag(values[, k]) | 设置数组/矩阵的对角线或非对角线元素。 | |
sign() | 逐元素的符号。 | |
sin() | 逐元素的 sin。 | |
sinh() | 逐元素的 sinh。 | |
sqrt() | 逐元素的平方根。 | |
sum([axis, dtype, out]) | 沿指定轴对数组/矩阵元素求和。 | |
tan() | 逐元素的 tan。 | |
tanh() | 逐元素双曲正切。 | |
toarray([order, out]) | 返回此稀疏数组/矩阵的稠密 ndarray 表示。 | |
tobsr([blocksize, copy]) | 将该数组/矩阵转换为块稀疏行格式。 | |
tocoo([copy]) | 将该数组/矩阵转换为坐标格式。 | |
tocsc([copy]) | 将该数组/矩阵转换为压缩稀疏列格式。 | |
tocsr([copy]) | 将该数组/矩阵转换为压缩稀疏行格式。 | |
todense([order, out]) | 返回此稀疏数组/矩阵的稠密表示。 | |
todia([copy]) | 将该数组/矩阵转换为稀疏对角格式。 | |
todok([copy]) | 将该数组/矩阵转换为键值对字典格式。 | |
tolil([copy]) | 将该数组/矩阵转换为列表列表格式。 | |
trace([offset]) | 返回稀疏数组/矩阵对角线上的元素和。 | |
transpose([axes, copy]) | 反转稀疏数组/矩阵的维度。 | |
trunc() | 逐元素截断。 |
scipy.sparse.dok_matrix
class scipy.sparse.dok_matrix(arg1, shape=None, dtype=None, copy=False)
基于键的稀疏矩阵。
这是逐步构建稀疏矩阵的高效结构。
可以通过几种方式实例化:
dok_matrix(D)
其中 D 为 2-D ndarray
dok_matrix(S)
与另一个稀疏数组或矩阵 S 一起(等同于 S.todok())
dok_matrix((M,N), [dtype])
使用初始形状为(M,N)的矩阵创建,dtype 为可选,默认为 dtype=’d’
注释
稀疏矩阵可用于算术操作:支持加法、减法、乘法、除法和矩阵幂。
-
允许以 O(1)的效率访问单个元素。
-
不允许重复。
-
构造后可高效转换为 coo_matrix。
示例
>>> import numpy as np
>>> from scipy.sparse import dok_matrix
>>> S = dok_matrix((5, 5), dtype=np.float32)
>>> for i in range(5):
... for j in range(5):
... S[i, j] = i + j # Update element
属性:
dtypedtype
矩阵的数据类型
shape2 元组
获取稀疏矩阵的形状。
ndim整型
维数(始终为 2)
存储值的数量,包括显式零值。
存储值的数量。
转置。
方法
__mul__(other) | |
|---|---|
asformat(format[, copy]) | 以传递的格式返回此数组/矩阵。 |
asfptype() | 将矩阵升级到浮点格式(如果需要) |
astype(dtype[, casting, copy]) | 将数组/矩阵元素转换为指定类型。 |
conj([copy]) | 逐元素复数共轭。 |
conjtransp() | 返回共轭转置。 |
conjugate([copy]) | 逐元素复数共轭。 |
copy() | 返回此数组/矩阵的副本。 |
count_nonzero() | 非零条目数量,等同于。 |
diagonal([k]) | 返回数组/矩阵的第 k 条对角线。 |
dot(other) | 普通的点积。 |
fromkeys(iterable[, value]) | 使用可迭代对象的键创建一个新字典,并将值设置为 value。 |
get(key[, default]) | 这覆盖了 dict.get 方法,提供类型检查但功能上相同。 |
getH() | 返回该矩阵的共轭转置。 |
get_shape() | 获取稀疏矩阵的形状。 |
getcol(j) | 返回矩阵的第 j 列的副本,作为一个 (m x 1) 稀疏矩阵(列向量)。 |
getformat() | 矩阵存储格式。 |
getmaxprint() | 打印时显示的最大元素数。 |
getnnz([axis]) | 存储值的数量,包括显式零。 |
getrow(i) | 返回矩阵第 i 行的副本,作为 (1 x n) 稀疏矩阵(行向量)。 |
maximum(other) | 该数组/矩阵与另一个数组/矩阵的逐元素最大值。 |
mean([axis, dtype, out]) | 沿指定轴计算算术平均值。 |
minimum(other) | 该数组/矩阵与另一个数组/矩阵的逐元素最小值。 |
multiply(other) | 与另一个数组/矩阵的逐点乘法。 |
nonzero() | 返回数组/矩阵的非零索引。 |
pop(key[, default]) | 如果找不到键key,则返回default,否则引发KeyError。 |
power(n[, dtype]) | 逐元素的幂运算。 |
reshape(self, shape[, order, copy]) | 给稀疏数组/矩阵赋予新的形状,但不改变其数据。 |
resize(*shape) | 原地调整数组/矩阵的尺寸为给定的shape。 |
set_shape(shape) | 原地设置矩阵的形状。 |
setdiag(values[, k]) | 设置数组/矩阵的对角线或非对角线元素。 |
sum([axis, dtype, out]) | 沿指定轴对数组/矩阵的元素求和。 |
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]) | 将此数组/矩阵转换为列表列表格式。 |
trace([offset]) | 返回稀疏数组/矩阵对角线上元素的和。 |
transpose([axes, copy]) | 反转稀疏数组/矩阵的维度。 |
| getitem | |
| len | |
| clear | |
| items | |
| keys | |
| popitem | |
| setdefault | |
| update | |
| values |
scipy.sparse.lil_matrix
class scipy.sparse.lil_matrix(arg1, shape=None, dtype=None, copy=False)
基于行的列表列表稀疏矩阵。
这是用于逐步构建稀疏矩阵的结构。请注意,在最坏情况下插入单个项可能需要线性时间;为了有效构建矩阵,请确保按行预先排序索引。
这可以通过几种方式实例化:
lil_matrix(D)
其中 D 是 2-D ndarray
lil_matrix(S)
与另一个稀疏数组或矩阵 S(相当于 S.tolil())。
lil_matrix((M, N), [dtype])
为了构建一个形状为(M, N)的空矩阵,dtype 是可选的,默认为 dtype='d'。
注意事项
稀疏矩阵可用于算术运算:支持加法、减法、乘法、除法和矩阵幂运算。
LIL 格式的优势
-
支持灵活的切片
-
矩阵稀疏结构的变化是高效的
LIL 格式的缺点
-
算术运算 LIL + LIL 很慢(考虑 CSR 或 CSC)
-
慢的列切片(考虑 CSC)
-
慢的矩阵向量乘积(考虑 CSR 或 CSC)
预期使用
-
LIL 格式对于构建稀疏矩阵很方便
-
一旦构建了矩阵,为了快速算术和矩阵向量操作,将其转换为 CSR 或 CSC 格式
-
在构建大型矩阵时考虑使用 COO 格式
数据结构
-
一个数组(
self.rows),其中每个元素都是非零元素的列索引的排序列表。 -
相应的非零值以类似的方式存储在
self.data中。
属性:
dtypedtype
矩阵的数据类型
shape2 元组
矩阵的形状
ndimint
维度数量(这总是 2)
存储的值的数量,包括显式零值。
存储的值的数量。
数据
LIL 格式矩阵的数据数组
行
LIL 格式矩阵的行索引数组
转置。
方法
__len__() | |
|---|---|
__mul__(other) | |
asformat(format[, copy]) | 将此数组/矩阵以指定格式返回。 |
asfptype() | 将矩阵转换为浮点数格式(如果必要)。 |
astype(dtype[, casting, copy]) | 将数组/矩阵元素转换为指定类型。 |
conj([copy]) | 对每个元素进行复数共轭。 |
conjugate | 对每个元素进行复数共轭。 |
copy() | 返回该数组/矩阵的副本。 |
count_nonzero() | 非零条目的数量,等同于... |
diagonal([k]) | 返回数组/矩阵的第 k 条对角线。 |
dot(other) | 普通的点积运算。 |
getH() | 返回该矩阵的共轭转置。 |
get_shape() | 获取矩阵的形状。 |
getcol(j) | 返回该矩阵的第 j 列的副本,作为(m x 1)稀疏矩阵(列向量)。 |
getformat() | 矩阵的存储格式。 |
getmaxprint() | 打印时显示的最大元素数量。 |
getnnz([axis]) | 存储的值的数量,包括显式的零值。 |
getrow(i) | 返回该矩阵的第 i 行的副本,作为(1 x n)稀疏矩阵(行向量)。 |
getrowview(i) | 返回第'i'行的视图(无需复制)。 |
maximum(other) | 该数组/矩阵与另一个数组/矩阵之间的逐元素最大值。 |
mean([axis, dtype, out]) | 计算沿指定轴的算术平均值。 |
minimum(other) | 此数组/矩阵与另一个数组/矩阵的逐元素最小值。 |
multiply(other) | 与另一个数组/矩阵进行逐点乘法。 |
nonzero() | 数组/矩阵的非零索引。 |
power(n[, dtype]) | 逐元素的幂运算。 |
reshape(self, shape[, order, copy]) | 给稀疏数组/矩阵赋予新的形状,但不更改其数据。 |
resize(*shape) | 就地调整数组/矩阵的尺寸为给定的shape维度。 |
set_shape(shape) | 就地设置矩阵的形状。 |
setdiag(values[, k]) | 设置数组/矩阵的对角线或非对角线元素。 |
sum([axis, dtype, out]) | 沿指定轴对数组/矩阵元素求和。 |
toarray([order, out]) | 返回此稀疏数组/矩阵的密集 ndarray 表示。 |
tobsr([blocksize, copy]) | 将此数组/矩阵转换为块稀疏行格式。 |
tocoo([copy]) | 将此数组/矩阵转换为坐标格式。 |
tocsc([copy]) | 将此数组/矩阵转换为压缩稀疏列格式。 |
tocsr([copy]) | 将此数组/矩阵转换为压缩稀疏行格式。 |
todense([order, out]) | 返回此稀疏数组/矩阵的密集表示。 |
todia([copy]) | 将该数组/矩阵转换为稀疏的对角线格式。 |
todok([copy]) | 将该数组/矩阵转换为字典键格式。 |
tolil([copy]) | 将该数组/矩阵转换为列表列表格式。 |
trace([offset]) | 返回稀疏数组/矩阵沿对角线的和。 |
transpose([axes, copy]) | 反转稀疏数组/矩阵的维度。 |
| getitem |
scipy.sparse.spmatrix
Original text:
docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.sparse.spmatrix.html#scipy.sparse.spmatrix
class scipy.sparse.spmatrix
此类为所有稀疏矩阵类提供了基类。
它不能被实例化。大部分工作由子类提供。
Attributes:
Shape of the matrix
Methods
__mul__(other) | ||
|---|---|---|
| - | asfptype() | 将矩阵提升为浮点格式(如有必要)。 |
| - | getH() | 返回该矩阵的共轭转置。 |
| - | get_shape() | 获取矩阵的形状。 |
| - | getcol(j) | 返回矩阵的第 j 列的副本,作为一个 (m x 1) 稀疏矩阵(列向量)。 |
| - | getformat() | 矩阵存储格式。 |
| - | getmaxprint() | 打印时显示的最大元素数。 |
| - | getnnz([axis]) | 存储值的数量,包括显式的零值。 |
| - | getrow(i) | 返回矩阵的第 i 行的副本,作为一个 (1 x n) 稀疏矩阵(行向量)。 |
| - | set_shape(shape) | 原地设置矩阵的形状。 |
scipy.sparse.diags_array
scipy.sparse.diags_array(diagonals, /, *, offsets=0, shape=None, format=None, dtype=None)
从对角线构造稀疏数组。
参数:
diagonals数组样式的序列
包含数组对角线的数组序列,对应于偏移。
offsets整数序列或整数,可选
要设置的对角线:
-
k = 0 主对角线(默认)
-
k > 0 第 k 个上对角线
-
k < 0 第 k 个下对角线
shape整数元组,可选
结果的形状。如果省略,将返回足够容纳对角线的方阵。
format{“dia”, “csr”, “csc”, “lil”, …},可选
结果的矩阵格式。默认情况下(format=None),返回适当的稀疏数组格式。此选择可能会更改。
dtypedtype,可选
数组的数据类型。
注意
diags_array的结果是稀疏等效于:
np.diag(diagonals[0], offsets[0])
+ ...
+ np.diag(diagonals[k], offsets[k])
不允许重复对角线偏移。
1.11 版新增。
示例
>>> from scipy.sparse import diags_array
>>> diagonals = [[1, 2, 3, 4], [1, 2, 3], [1, 2]]
>>> diags_array(diagonals, offsets=[0, -1, 2]).toarray()
array([[1, 0, 1, 0],
[1, 2, 0, 2],
[0, 2, 3, 0],
[0, 0, 3, 4]])
支持标量的广播(但需要指定形状):
>>> diags_array([1, -2, 1], offsets=[-1, 0, 1], shape=(4, 4)).toarray()
array([[-2., 1., 0., 0.],
[ 1., -2., 1., 0.],
[ 0., 1., -2., 1.],
[ 0., 0., 1., -2.]])
如果只需要一个对角线(如numpy.diag中),以下内容同样适用:
>>> diags_array([1, 2, 3], offsets=1).toarray()
array([[ 0., 1., 0., 0.],
[ 0., 0., 2., 0.],
[ 0., 0., 0., 3.],
[ 0., 0., 0., 0.]])
scipy.sparse.eye_array
scipy.sparse.eye_array(m, n=None, *, k=0, dtype=<class 'float'>, format=None)
稀疏数组格式的单位矩阵
返回一个稀疏数组,对角线上为 1。具体为稀疏数组(m x n),其中第 k 个对角线上全为 1,其他位置为 0。
参数:
m整数或整数元组
请求的行数。
n整数,可选
列数。默认为m。
k整数,可选
放置 1 的对角线。默认为 0(主对角线)。
dtype数据类型,可选
数组的数据类型
format字符串,可选(默认为“dia”)
结果的稀疏格式,例如,format=”csr”等。
示例
>>> import numpy as np
>>> import scipy as sp
>>> sp.sparse.eye_array(3).toarray()
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
>>> sp.sparse.eye_array(3, dtype=np.int8)
<3x3 sparse array of type '<class 'numpy.int8'>'
with 3 stored elements (1 diagonals) in DIAgonal format>
scipy.sparse.random_array
scipy.sparse.random_array(shape, *, density=0.01, format='coo', dtype=None, random_state=None, data_sampler=None)
返回在[0, 1)中均匀随机的稀疏数组
返回一个给定形状和密度的稀疏数组,其中值在范围[0, 1)内均匀随机生成。
警告
自 numpy 1.17 起,为random_state传递np.random.Generator(例如np.random.default_rng)将导致执行时间大大加快。
默认情况下使用更慢的实现以保持向后兼容性。
参数:
shape:int 或 int 元组
数组的形状
density:实数,可选(默认值:0.01)
生成矩阵的密度:密度为 1 表示完整矩阵,密度为 0 表示没有非零项的矩阵。
format:str,可选(默认值:'coo')
稀疏矩阵格式。
dtype:dtype,可选(默认值:np.float64)
返回矩阵值的类型。
random_state:{None, int, Generator, RandomState},可选
用于确定非零结构的随机数生成器。我们建议每次调用手动提供一个numpy.random.Generator,因为它比 RandomState 快得多。
-
如果为None(或np.random),则使用
numpy.random.RandomState单例。 -
如果是整数,将使用新的
Generator实例,并以该整数作为种子。 -
如果是
Generator或RandomState实例,则使用该实例。
这个随机状态将用于采样索引(稀疏结构),默认情况下也用于数据值(见data_sampler)。
data_sampler:可调用对象,可选(默认取决于 dtype)
具有关键字参数size的随机数据值取样器。此函数应接受一个关键字参数size,指定其返回的 ndarray 的长度。它用于在选择这些值的位置后生成矩阵中的非零值。默认情况下,使用均匀分布的[0, 1)随机值,除非dtype是整数(默认从该 dtype 生成均匀整数)或复数(默认在复平面单位正方形上均匀分布)。对于这些情况,使用random_state RNG,例如rng.uniform(size=size)。
返回:
res:稀疏数组
示例
传递np.random.Generator实例以获得更好的性能:
>>> import numpy as np
>>> import scipy as sp
>>> rng = np.random.default_rng()
默认从[0, 1)均匀采样:
>>> S = sp.sparse.random_array((3, 4), density=0.25, random_state=rng)
提供值的取样器:
>>> rvs = sp.stats.poisson(25, loc=10).rvs
>>> S = sp.sparse.random_array((3, 4), density=0.25,
... random_state=rng, data_sampler=rvs)
>>> S.toarray()
array([[ 36., 0., 33., 0.], # random
[ 0., 0., 0., 0.],
[ 0., 0., 36., 0.]])
构建自定义分布。此示例从 np.random 构建了一个平方正态分布:
>>> def np_normal_squared(size=None, random_state=rng):
... return random_state.standard_normal(size) ** 2
>>> S = sp.sparse.random_array((3, 4), density=0.25, random_state=rng,
... data_sampler=np_normal_squared)
或者我们可以从 sp.stats 风格的 rvs 函数构建它:
>>> def sp_stats_normal_squared(size=None, random_state=rng):
... std_normal = sp.stats.distributions.norm_gen().rvs
... return std_normal(size=size, random_state=random_state) ** 2
>>> S = sp.sparse.random_array((3, 4), density=0.25, random_state=rng,
... data_sampler=sp_stats_normal_squared)
或者我们可以子类化 sp.stats rv_continous 或 rv_discrete:
>>> class NormalSquared(sp.stats.rv_continuous):
... def _rvs(self, size=None, random_state=rng):
... return random_state.standard_normal(size) ** 2
>>> X = NormalSquared()
>>> Y = X().rvs
>>> S = sp.sparse.random_array((3, 4), density=0.25,
... random_state=rng, data_sampler=Y)
scipy.sparse.block_array
scipy.sparse.block_array(blocks, *, format=None, dtype=None)
从稀疏子块构建稀疏数组
参数:
块array_like
具有兼容形状的稀疏数组网格。None 表示全零数组。
格式{‘bsr’, ‘coo’, ‘csc’, ‘csr’, ‘dia’, ‘dok’, ‘lil’},可选
结果的稀疏格式(例如“csr”)。默认情况下返回适当的稀疏数组格式。此选择可能会更改。
dtypedtype,可选
输出数组的数据类型。如果未给出,则从blocks的数据类型确定。
返回:
块稀疏数组
另请参阅
指定沿主对角线的块
指定(可能有偏移的)对角线
示例
>>> from scipy.sparse import coo_array, block_array
>>> A = coo_array([[1, 2], [3, 4]])
>>> B = coo_array([[5], [6]])
>>> C = coo_array([[7]])
>>> block_array([[A, B], [None, C]]).toarray()
array([[1, 2, 5],
[3, 4, 6],
[0, 0, 7]])
>>> block_array([[A, None], [None, C]]).toarray()
array([[1, 2, 0],
[3, 4, 0],
[0, 0, 7]])
scipy.sparse.eye
原文:
docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.sparse.eye.html#scipy.sparse.eye
scipy.sparse.eye(m, n=None, k=0, dtype=<class 'float'>, format=None)
对角线上有 1 的稀疏矩阵
返回一个稀疏矩阵(m x n),其中第 k 个对角线上全为 1,其余为 0。
参数:
mint
矩阵中的行数。
nint,可选
列数。默认值:m。
kint,可选
放置 1 的对角线。默认值:0(主对角线)。
dtypedtype,可选
矩阵的数据类型。
formatstr,可选
结果的稀疏格式,例如,format=”csr”等。
.. warning::
此函数返回一个稀疏矩阵,而不是稀疏数组。建议使用eye_array来利用稀疏数组的功能。
示例
>>> import numpy as np
>>> import scipy as sp
>>> sp.sparse.eye(3).toarray()
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
>>> sp.sparse.eye(3, dtype=np.int8)
<3x3 sparse matrix of type '<class 'numpy.int8'>'
with 3 stored elements (1 diagonals) in DIAgonal format>
scipy.sparse.identity
原文链接:
docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.sparse.identity.html#scipy.sparse.identity
scipy.sparse.identity(n, dtype='d', format=None)
稀疏格式的单位矩阵
返回一个形状为(n,n)的单位矩阵,使用给定的稀疏格式和 dtype。这与eye_array不同,后者具有方形形状,只有在主对角线上有 1。因此它是乘法单位。eye_array允许矩形形状,对角线可以偏离主对角线。
警告
此函数返回稀疏矩阵,而不是稀疏数组。建议您使用eye_array以利用稀疏数组的功能。
参数:
nint
单位矩阵的形状。
dtypedtype,可选
矩阵的数据类型
格式str,可选
结果的稀疏格式,例如,format=”csr”等。
示例
>>> import scipy as sp
>>> sp.sparse.identity(3).toarray()
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
>>> sp.sparse.identity(3, dtype='int8', format='dia')
<3x3 sparse matrix of type '<class 'numpy.int8'>'
with 3 stored elements (1 diagonals) in DIAgonal format>
>>> sp.sparse.eye_array(3, dtype='int8', format='dia')
<3x3 sparse array of type '<class 'numpy.int8'>'
with 3 stored elements (1 diagonals) in DIAgonal format>
scipy.sparse.diags
原文链接:
docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.sparse.diags.html#scipy.sparse.diags
scipy.sparse.diags(diagonals, offsets=0, shape=None, format=None, dtype=None)
从对角线构建稀疏矩阵。
警告
此函数返回稀疏矩阵 – 而不是稀疏数组。建议您使用diags_array来利用稀疏数组功能。
参数:
diagonals数组序列
包含矩阵对角线的数组序列,对应于offsets。
offsets整数序列或整数,可选
要设置的对角线:
-
k = 0 主对角线(默认)
-
k > 0 第 k 个上对角线
-
k < 0 第 k 个下对角线
shape整数元组,可选
结果的形状。如果省略,将返回一个足够大以包含对角线的方阵。
format{“dia”, “csr”, “csc”, “lil”, …},可选
结果的矩阵格式。默认情况下(format=None),将返回适当的稀疏矩阵格式。此选择可能会更改。
dtypedtype,可选
矩阵的数据类型。
另请参阅
spdiags
从对角线构建矩阵
diags_array
构建稀疏数组而不是稀疏矩阵
注意事项
此函数与spdiags在处理非对角线元素的方式上有所不同。
diags的结果是稀疏等价于:
np.diag(diagonals[0], offsets[0])
+ ...
+ np.diag(diagonals[k], offsets[k])
禁止重复的对角线偏移。
从版本 0.11 开始新增。
示例
>>> from scipy.sparse import diags
>>> diagonals = [[1, 2, 3, 4], [1, 2, 3], [1, 2]]
>>> diags(diagonals, [0, -1, 2]).toarray()
array([[1, 0, 1, 0],
[1, 2, 0, 2],
[0, 2, 3, 0],
[0, 0, 3, 4]])
支持标量的广播(但需要指定形状):
>>> diags([1, -2, 1], [-1, 0, 1], shape=(4, 4)).toarray()
array([[-2., 1., 0., 0.],
[ 1., -2., 1., 0.],
[ 0., 1., -2., 1.],
[ 0., 0., 1., -2.]])
如果只想要一个对角线(如numpy.diag中所述),以下方法同样适用:
>>> diags([1, 2, 3], 1).toarray()
array([[ 0., 1., 0., 0.],
[ 0., 0., 2., 0.],
[ 0., 0., 0., 3.],
[ 0., 0., 0., 0.]])
scipy.sparse.spdiags
原文:
docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.sparse.spdiags.html#scipy.sparse.spdiags
scipy.sparse.spdiags(data, diags, m=None, n=None, format=None)
从对角线返回稀疏矩阵。
参数:
dataarray_like
矩阵对角线按行存储
diags整数或整数序列
要设置的对角线:
-
k = 0 主对角线
-
k > 0 第 k 个上对角线
-
k < 0 第 k 个下对角线
m, n整数,元组,可选
结果的形状。如果n为 None 且m为给定的元组,则形状是这个元组。如果省略,则矩阵是方阵,其形状为 len(data[0])。
format字符串,可选
结果的格式。默认情况下(format=None),返回适当的稀疏矩阵格式。此选择可能会更改。
.. 警告::
此函数返回稀疏矩阵 - 而不是稀疏数组。建议使用diags_array以利用稀疏数组功能。
另请参阅
更方便的此函数形式
diags_array 的矩阵版本
稀疏 DIAgonal 格式。
示例
>>> import numpy as np
>>> from scipy.sparse import spdiags
>>> data = np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]])
>>> diags = np.array([0, -1, 2])
>>> spdiags(data, diags, 4, 4).toarray()
array([[1, 0, 3, 0],
[1, 2, 0, 4],
[0, 2, 3, 0],
[0, 0, 3, 4]])
scipy.sparse.bmat
原文:
docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.sparse.bmat.html#scipy.sparse.bmat
scipy.sparse.bmat(blocks, format=None, dtype=None)
从稀疏子块构建稀疏数组或矩阵
注意:block_array 优先于 bmat。它们是相同的函数,除了 bmat 可能会返回一个已弃用的稀疏矩阵。如果输入的所有内容都不是稀疏数组,则 bmat 返回一个 coo_matrix。
警告
此函数返回一个稀疏矩阵 - 而不是稀疏数组。建议使用 block_array 来利用稀疏数组的功能。
参数:
blocksarray_like
具有兼容形状的稀疏矩阵网格。None 表示全零矩阵。
格式{‘bsr’, ‘coo’, ‘csc’, ‘csr’, ‘dia’, ‘dok’, ‘lil’},可选
结果的稀疏格式(例如“csr”)。默认情况下会返回适当的稀疏矩阵格式。这种选择可能会改变。
dtypedtype,可选
输出矩阵的数据类型。如果未提供,则从 blocks 的数据类型确定。
返回:
bmat稀疏矩阵或数组
如果 blocks 中的任何块是稀疏数组,则返回稀疏数组。否则返回稀疏矩阵。
如果希望从非稀疏数组的块构建稀疏数组,请使用 block_array()。
另请参见
示例
>>> from scipy.sparse import coo_array, bmat
>>> A = coo_array([[1, 2], [3, 4]])
>>> B = coo_array([[5], [6]])
>>> C = coo_array([[7]])
>>> bmat([[A, B], [None, C]]).toarray()
array([[1, 2, 5],
[3, 4, 6],
[0, 0, 7]])
>>> bmat([[A, None], [None, C]]).toarray()
array([[1, 2, 0],
[3, 4, 0],
[0, 0, 7]])
scipy.sparse.random
原文:
docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.sparse.random.html#scipy.sparse.random
scipy.sparse.random(m, n, density=0.01, format='coo', dtype=None, random_state=None, data_rvs=None)
以给定形状和密度生成稀疏矩阵,其值是随机分布的。
警告
自 numpy 1.17 起,传递np.random.Generator(例如np.random.default_rng)作为random_state将导致执行时间大大缩短。
默认情况下,为了向后兼容性使用了一个较慢的实现。
警告
此函数返回稀疏矩阵 – 而不是稀疏数组。建议您使用random_array来利用稀疏数组功能。
参数:
m, nint
矩阵的形状
密度real, 可选
生成矩阵的密度:密度等于一表示完整矩阵,密度为零表示没有非零项的矩阵。
格式str, 可选
稀疏矩阵格式。
dtypedtype, 可选
返回矩阵值的类型。
随机状态{None, int, numpy.random.Generator,
-
如果seed为 None(或np.random),则使用
numpy.random.RandomState单例。 -
如果seed是一个整数,则使用一个新的
RandomState实例,并用seed进行种子化。 -
如果seed已经是一个
Generator或RandomState实例,则使用该实例。
此随机状态将用于采样稀疏矩阵的非结构化非零条目的值,但不一定用于采样结构非零条目的值。
data_rvscallable, 可选
样本请求数量的随机值。此函数应该接受一个参数,指定它将返回的 ndarray 的长度。稀疏随机矩阵的结构化非零条目将从此函数采样的数组中获取。默认情况下,将使用与用于采样稀疏性结构的随机状态相同的均匀 0, 1)随机值进行采样。
返回:
res稀疏矩阵
另请参阅
[random_array
构建稀疏数组而不是稀疏矩阵
示例
为了更好的性能,传递一个np.random.Generator实例:
>>> import scipy as sp
>>> import numpy as np
>>> rng = np.random.default_rng()
>>> S = sp.sparse.random(3, 4, density=0.25, random_state=rng)
为值提供一个采样器:
>>> rvs = sp.stats.poisson(25, loc=10).rvs
>>> S = sp.sparse.random(3, 4, density=0.25, random_state=rng, data_rvs=rvs)
>>> S.toarray()
array([[ 36., 0., 33., 0.], # random
[ 0., 0., 0., 0.],
[ 0., 0., 36., 0.]])
构建自定义分布。此示例从 np.random 构建了一个平方正态分布:
>>> def np_normal_squared(size=None, random_state=rng):
... return random_state.standard_normal(size) ** 2
>>> S = sp.sparse.random(3, 4, density=0.25, random_state=rng,
... data_rvs=np_normal_squared)
或者我们可以从 sp.stats 风格的 rvs 函数构建它:
>>> def sp_stats_normal_squared(size=None, random_state=rng):
... std_normal = sp.stats.distributions.norm_gen().rvs
... return std_normal(size=size, random_state=random_state) ** 2
>>> S = sp.sparse.random(3, 4, density=0.25, random_state=rng,
... data_rvs=sp_stats_normal_squared)
或者我们可以子类化 sp.stats rv_continuous 或 rv_discrete:
>>> class NormalSquared(sp.stats.rv_continuous):
... def _rvs(self, size=None, random_state=rng):
... return random_state.standard_normal(size) ** 2
>>> X = NormalSquared()
>>> Y = X() # get a frozen version of the distribution
>>> S = sp.sparse.random(3, 4, density=0.25, random_state=rng, data_rvs=Y.rvs)
scipy.sparse.rand
原文:
docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.sparse.rand.html#scipy.sparse.rand
scipy.sparse.rand(m, n, density=0.01, format='coo', dtype=None, random_state=None)
生成具有均匀分布值的给定形状和密度的稀疏矩阵。
警告
此函数返回一个稀疏矩阵 - 而不是稀疏数组。建议使用 random_array 利用稀疏数组功能。
参数:
m, n整数
矩阵的形状
density实数,可选
生成矩阵的密度:密度为一表示完整矩阵,密度为 0 表示没有非零项的矩阵。
formatstr,可选
稀疏矩阵格式。
dtypedtype,可选
返回矩阵值类型。
random_state{None, int, numpy.random.Generator,
如果 seed 为 None(或 np.random),则使用 numpy.random.RandomState 单例。如果 seed 是整数,则使用种子为 seed 的新 RandomState 实例。如果 seed 已经是 Generator 或 RandomState 实例,则使用该实例。
返回:
res稀疏矩阵
另请参阅
random
允许自定义随机数据采样器的类似函数
random_array
类似于 random() 但返回稀疏数组
注意事项
目前仅支持浮点类型。
示例
>>> from scipy.sparse import rand
>>> matrix = rand(3, 4, density=0.25, format="csr", random_state=42)
>>> matrix
<3x4 sparse matrix of type '<class 'numpy.float64'>'
with 3 stored elements in Compressed Sparse Row format>
>>> matrix.toarray()
array([[0.05641158, 0\. , 0\. , 0.65088847], # random
[0\. , 0\. , 0\. , 0.14286682],
[0\. , 0\. , 0\. , 0\. ]])
scipy.sparse.kron
原文:
docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.sparse.kron.html#scipy.sparse.kron
scipy.sparse.kron(A, B, format=None)
稀疏矩阵 A 和 B 的克罗内克积
参数:
A 稀疏或密集矩阵
乘积的第一个矩阵
B 稀疏或密集矩阵
乘积的第二个矩阵
format str,可选(默认为 ‘bsr’ 或 ‘coo’)
结果的格式(例如,“csr”)。如果为 None,则对相对密集的数组选择“bsr”,对其他情况选择“coo”。
返回:
克罗内克积的稀疏格式。
除非 A 或 B 是稠密矩阵,否则返回稀疏矩阵。
稀疏数组在这种情况下返回稀疏数组。
示例
>>> import numpy as np
>>> import scipy as sp
>>> A = sp.sparse.csr_array(np.array([[0, 2], [5, 0]]))
>>> B = sp.sparse.csr_array(np.array([[1, 2], [3, 4]]))
>>> sp.sparse.kron(A, B).toarray()
array([[ 0, 0, 2, 4],
[ 0, 0, 6, 8],
[ 5, 10, 0, 0],
[15, 20, 0, 0]])
>>> sp.sparse.kron(A, [[1, 2], [3, 4]]).toarray()
array([[ 0, 0, 2, 4],
[ 0, 0, 6, 8],
[ 5, 10, 0, 0],
[15, 20, 0, 0]])
scipy.sparse.kronsum
原文:
docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.sparse.kronsum.html#scipy.sparse.kronsum
scipy.sparse.kronsum(A, B, format=None)
方阵 A 和 B 的 Kronecker 和
两个稀疏矩阵的 Kronecker 和是两个 Kronecker 积 kron(I_n,A) + kron(B,I_m)的和,其中 A 的形状为(m,m),B 的形状为(n,n),而 I_m 和 I_n 分别是形状为(m,m)和(n,n)的单位矩阵。
参数:
A
方阵
B
方阵
formatstr
结果的格式(例如“csr”)
返回结果:
稀疏矩阵中的 Kronecker 和
scipy.sparse.block_diag
scipy.sparse.block_diag(mats, format=None, dtype=None)
从提供的矩阵构建块对角稀疏矩阵或数组。
参数:
mats 矩阵或数组序列
输入的矩阵或数组。
format str,可选
结果的稀疏格式(例如,“csr”)。如果未给出,则以“coo”格式返回结果。
dtype dtype 指定器,可选
输出的数据类型。如果未给出,则从blocks的数据类型确定。
返回:
res 稀疏矩阵或数组
如果至少有一个输入是稀疏数组,则输出为稀疏数组。否则输出为稀疏矩阵。
另请参阅
block_array
diags_array
注意
新版本 0.11.0 中引入。
示例
>>> from scipy.sparse import coo_array, block_diag
>>> A = coo_array([[1, 2], [3, 4]])
>>> B = coo_array([[5], [6]])
>>> C = coo_array([[7]])
>>> block_diag((A, B, C)).toarray()
array([[1, 2, 0, 0],
[3, 4, 0, 0],
[0, 0, 5, 0],
[0, 0, 6, 0],
[0, 0, 0, 7]])
scipy.sparse.tril
原文链接:
docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.sparse.tril.html#scipy.sparse.tril
scipy.sparse.tril(A, k=0, format=None)
返回稀疏数组或矩阵的下三角部分
返回矩阵 A 的第 k 条对角线上方或其对角线上的元素。
-
k = 0 对应于主对角线
-
k > 0 位于主对角线之上
-
k < 0 位于主对角线之下
参数:
A密集或稀疏数组或矩阵
所需矩阵的下三角部分。
k整数可选
下三角形的最顶部对角线。
format字符串
结果的稀疏格式,例如 format=”csr”等。
返回:
L稀疏矩阵
矩阵 A 的稀疏格式下的下三角部分。
另请参见
稀疏格式中的上三角形式
示例
>>> from scipy.sparse import csr_array, tril
>>> A = csr_array([[1, 2, 0, 0, 3], [4, 5, 0, 6, 7], [0, 0, 8, 9, 0]],
... dtype='int32')
>>> A.toarray()
array([[1, 2, 0, 0, 3],
[4, 5, 0, 6, 7],
[0, 0, 8, 9, 0]])
>>> tril(A).toarray()
array([[1, 0, 0, 0, 0],
[4, 5, 0, 0, 0],
[0, 0, 8, 0, 0]])
>>> tril(A).nnz
4
>>> tril(A, k=1).toarray()
array([[1, 2, 0, 0, 0],
[4, 5, 0, 0, 0],
[0, 0, 8, 9, 0]])
>>> tril(A, k=-1).toarray()
array([[0, 0, 0, 0, 0],
[4, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
>>> tril(A, format='csc')
<3x5 sparse array of type '<class 'numpy.int32'>'
with 4 stored elements in Compressed Sparse Column format>
scipy.sparse.triu
原文:
docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.sparse.triu.html#scipy.sparse.triu
scipy.sparse.triu(A, k=0, format=None)
返回稀疏数组或矩阵的上三角部分
返回矩阵 A 的第 k 条对角线及其以上的元素。
-
k = 0 对应于主对角线
-
k > 0 在主对角线上方
-
k < 0 在主对角线下方
参数:
A密集或稀疏的数组或矩阵
所需获取其上三角部分的矩阵。
k整数可选
上三角的最底部对角线。
format字符串
结果的稀疏格式,例如 format=”csr” 等。
返回:
L稀疏的数组或矩阵
A 的稀疏格式的上三角部分。如果 A 是稀疏数组,则返回稀疏数组,否则返回矩阵。
另请参阅
tril
稀疏格式的下三角
示例
>>> from scipy.sparse import csr_array, triu
>>> A = csr_array([[1, 2, 0, 0, 3], [4, 5, 0, 6, 7], [0, 0, 8, 9, 0]],
... dtype='int32')
>>> A.toarray()
array([[1, 2, 0, 0, 3],
[4, 5, 0, 6, 7],
[0, 0, 8, 9, 0]])
>>> triu(A).toarray()
array([[1, 2, 0, 0, 3],
[0, 5, 0, 6, 7],
[0, 0, 8, 9, 0]])
>>> triu(A).nnz
8
>>> triu(A, k=1).toarray()
array([[0, 2, 0, 0, 3],
[0, 0, 0, 6, 7],
[0, 0, 0, 9, 0]])
>>> triu(A, k=-1).toarray()
array([[1, 2, 0, 0, 3],
[4, 5, 0, 6, 7],
[0, 0, 8, 9, 0]])
>>> triu(A, format='csc')
<3x5 sparse array of type '<class 'numpy.int32'>'
with 8 stored elements in Compressed Sparse Column format>
scipy.sparse.hstack
原文:
docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.sparse.hstack.html#scipy.sparse.hstack
scipy.sparse.hstack(blocks, format=None, dtype=None)
水平堆叠稀疏矩阵(按列堆叠)
参数:
blocks
具有兼容形状的稀疏矩阵序列
格式str
返回结果的稀疏格式(例如,“csr”),默认情况下返回适当的稀疏矩阵格式。此选择可能会更改。
dtypedtype,可选
输出矩阵的数据类型。如果未指定,则从blocks中确定。
返回:
new_array稀疏矩阵或数组
如果 blocks 中的任何块是稀疏数组,则返回稀疏数组。否则返回稀疏矩阵。
如果您希望从非稀疏数组构建稀疏数组,使用block(hstack(blocks))或转换一个块,例如blocks[0] = csr_array(blocks[0])。
另请参见
vstack
垂直堆叠稀疏矩阵(按行堆叠)
示例
>>> from scipy.sparse import coo_matrix, hstack
>>> A = coo_matrix([[1, 2], [3, 4]])
>>> B = coo_matrix([[5], [6]])
>>> hstack([A,B]).toarray()
array([[1, 2, 5],
[3, 4, 6]])
scipy.sparse.vstack
原文:
docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.sparse.vstack.html#scipy.sparse.vstack
scipy.sparse.vstack(blocks, format=None, dtype=None)
垂直堆叠稀疏数组(按行)
参数:
blocks
兼容形状的稀疏数组序列
formatstr,可选
结果的稀疏格式(例如,“csr”)默认情况下返回适当的稀疏数组格式。此选择可能会更改。
dtypedtype,可选
输出数组的数据类型。如果未指定,则从blocks的数据类型确定。
返回:
new_array稀疏矩阵或数组
如果 blocks 中的任何一个块是稀疏数组,则返回稀疏数组。否则返回稀疏矩阵。
如果您希望从非稀疏数组块构建稀疏数组,请使用block(vstack(blocks))或转换一个块,例如blocks[0] = csr_array(blocks[0])。
参见
hstack
水平堆叠稀疏矩阵(按列)
示例
>>> from scipy.sparse import coo_array, vstack
>>> A = coo_array([[1, 2], [3, 4]])
>>> B = coo_array([[5, 6]])
>>> vstack([A, B]).toarray()
array([[1, 2],
[3, 4],
[5, 6]])
scipy.sparse.save_npz
原文:
docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.sparse.save_npz.html#scipy.sparse.save_npz
scipy.sparse.save_npz(file, matrix, compressed=True)
将稀疏矩阵或数组保存到文件中,使用.npz格式。
参数:
文件str 或类文件对象
文件名(字符串)或数据将保存到的打开文件(类文件对象)。如果文件是字符串,则如果文件名尚未包含.npz扩展名,则将其添加到文件名中。
矩阵:spmatrix 或 sparray
要保存的稀疏矩阵或数组。支持的格式:csc、csr、bsr、dia 或 coo。
压缩bool, 可选
允许压缩文件。默认:True
另请参阅
scipy.sparse.load_npz
从文件中使用.npz格式加载稀疏矩阵。
将多个数组保存到.npz归档文件中。
将多个数组保存到压缩的.npz归档文件中。
示例
将稀疏矩阵存储到磁盘,并再次加载:
>>> import numpy as np
>>> import scipy as sp
>>> sparse_matrix = sp.sparse.csc_matrix([[0, 0, 3], [4, 0, 0]])
>>> sparse_matrix
<2x3 sparse matrix of type '<class 'numpy.int64'>'
with 2 stored elements in Compressed Sparse Column format>
>>> sparse_matrix.toarray()
array([[0, 0, 3],
[4, 0, 0]], dtype=int64)
>>> sp.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix)
>>> sparse_matrix = sp.sparse.load_npz('/tmp/sparse_matrix.npz')
>>> sparse_matrix
<2x3 sparse matrix of type '<class 'numpy.int64'>'
with 2 stored elements in Compressed Sparse Column format>
>>> sparse_matrix.toarray()
array([[0, 0, 3],
[4, 0, 0]], dtype=int64)
scipy.sparse.load_npz
原文:
docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.sparse.load_npz.html#scipy.sparse.load_npz
scipy.sparse.load_npz(file)
使用.npz格式从文件加载稀疏数组/矩阵。
参数:
filestr 或类文件对象
要么是文件名(字符串),要么是一个打开的文件(类似文件对象),其中数据将被加载。
返回:
resultcsc_array, csr_array, bsr_array, dia_array 或 coo_array
包含加载数据的稀疏数组/矩阵。
引发:
OSError
如果输入文件不存在或无法读取。
另请参阅
scipy.sparse.save_npz
使用.npz格式将稀疏数组/矩阵保存到文件中。
从.npz存档中加载多个数组。
示例
将稀疏数组/矩阵存储到磁盘上,并再次加载:
>>> import numpy as np
>>> import scipy as sp
>>> sparse_array = sp.sparse.csc_array([[0, 0, 3], [4, 0, 0]])
>>> sparse_array
<2x3 sparse array of type '<class 'numpy.int64'>'
with 2 stored elements in Compressed Sparse Column format>
>>> sparse_array.toarray()
array([[0, 0, 3],
[4, 0, 0]], dtype=int64)
>>> sp.sparse.save_npz('/tmp/sparse_array.npz', sparse_array)
>>> sparse_array = sp.sparse.load_npz('/tmp/sparse_array.npz')
>>> sparse_array
<2x3 sparse array of type '<class 'numpy.int64'>'
with 2 stored elements in Compressed Sparse Column format>
>>> sparse_array.toarray()
array([[0, 0, 3],
[4, 0, 0]], dtype=int64)
在这个例子中,我们强制结果为 csr_array,从 csr_matrix >>> sparse_matrix = sp.sparse.csc_matrix([[0, 0, 3], [4, 0, 0]]) >>> sp.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix) >>> tmp = sp.sparse.load_npz('/tmp/sparse_matrix.npz') >>> sparse_array = sp.sparse.csr_array(tmp)
scipy.sparse.find
原文:
docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.sparse.find.html#scipy.sparse.find
scipy.sparse.find(A)
返回矩阵非零元素的索引和值
参数:
A 密集或稀疏数组或矩阵
需要非零元素的矩阵。
返回:
(I,J,V) 由数组组成的元组
I、J 和 V 包含非零条目的行索引、列索引和值。
示例
>>> from scipy.sparse import csr_array, find
>>> A = csr_array([[7.0, 8.0, 0],[0, 0, 9.0]])
>>> find(A)
(array([0, 0, 1], dtype=int32),
array([0, 1, 2], dtype=int32),
array([ 7., 8., 9.]))
scipy.sparse.issparse
原文:
docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.sparse.issparse.html#scipy.sparse.issparse
scipy.sparse.issparse(x)
x 是否是稀疏数组或稀疏矩阵类型?
参数:
x
用于检查是否为稀疏数组或稀疏矩阵的对象
返回:
布尔值
如果 x 是稀疏数组或稀疏矩阵,则返回 True,否则返回 False
示例
>>> import numpy as np
>>> from scipy.sparse import csr_array, csr_matrix, issparse
>>> issparse(csr_matrix([[5]]))
True
>>> issparse(csr_array([[5]]))
True
>>> issparse(np.array([[5]]))
False
>>> issparse(5)
False
scipy.sparse.isspmatrix
scipy.sparse.isspmatrix(x)
x 是否为稀疏矩阵类型?
参数:
x
检查是否为稀疏矩阵的对象
返回:
布尔值
如果 x 是稀疏矩阵则返回 True,否则返回 False
示例
>>> import numpy as np
>>> from scipy.sparse import csr_array, csr_matrix, isspmatrix
>>> isspmatrix(csr_matrix([[5]]))
True
>>> isspmatrix(csr_array([[5]]))
False
>>> isspmatrix(np.array([[5]]))
False
>>> isspmatrix(5)
False
scipy.sparse.isspmatrix_csc
scipy.sparse.isspmatrix_csc(x)
x是否为 csc_matrix 类型?
参数:
x
要检查是否为 csc 矩阵的对象
返回:
布尔值
如果x是 csc 矩阵,则为 True,否则为 False
示例
>>> from scipy.sparse import csc_array, csc_matrix, coo_matrix, isspmatrix_csc
>>> isspmatrix_csc(csc_matrix([[5]]))
True
>>> isspmatrix_csc(csc_array([[5]]))
False
>>> isspmatrix_csc(coo_matrix([[5]]))
False
scipy.sparse.isspmatrix_csr
scipy.sparse.isspmatrix_csr(x)
x是 csr_matrix 类型吗?
参数:
x
要检查是否为 csr 矩阵的对象。
返回:
布尔值
如果x是 csr 矩阵,则为 True,否则为 False。
示例
>>> from scipy.sparse import csr_array, csr_matrix, coo_matrix, isspmatrix_csr
>>> isspmatrix_csr(csr_matrix([[5]]))
True
>>> isspmatrix_csr(csr_array([[5]]))
False
>>> isspmatrix_csr(coo_matrix([[5]]))
False