将 scipy 稀疏矩阵的几行采样到另一个中

2024-05-22

如何对 scipy 稀疏矩阵的某些行进行采样,并从这些采样的行中形成一个新的 scipy 稀疏矩阵?

例如。如果我有一个 10 行的 scipy 稀疏矩阵 A,并且我想创建一个新的 scipy 稀疏矩阵 B,其中 A 的第 1、3、4 行,该怎么做?


左乘适当的指标矩阵。指标矩阵可以使用以下方式构建scipy.sparse.block_diag或者直接使用 csr 格式,如下所示。

>>> import numpy as np
>>> from scipy import sparse
>>> 
# create example
>>> m, n = 10, 8
>>> subset = [1,3,4]
>>> A = sparse.csr_matrix(np.random.randint(-10, 5, (m, n)).clip(0, None))
>>> A.A
array([[3, 2, 4, 0, 0, 0, 2, 0],
       [0, 0, 2, 0, 0, 0, 0, 0],
       [4, 0, 0, 0, 0, 2, 0, 0],
       [0, 0, 0, 0, 0, 0, 4, 0],
       [3, 0, 0, 0, 1, 4, 0, 0],
       [0, 0, 0, 0, 0, 0, 2, 0],
       [0, 0, 0, 4, 0, 4, 4, 0],
       [0, 2, 0, 0, 0, 3, 0, 0],
       [4, 0, 3, 3, 0, 0, 0, 2],
       [4, 0, 0, 0, 0, 2, 0, 1]], dtype=int64)
>>>
# build indicator matrix
# either using block_diag ...
>>> split_points = np.arange(len(subset)+1).repeat(np.diff(np.concatenate([[0], subset, [m-1]])))
>>> indicator = sparse.block_diag(np.split(np.ones(len(subset), int), split_points)).T
>>> indicator.A
array([[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 0, 0, 0, 0, 0]], dtype=int64)
>>>
# ... or manually---this also works for non sorted non unique subset,
# and is therefore to be preferred over block_diag
>>> indicator = sparse.csr_matrix((np.ones(len(subset), int), subset, np.arange(len(subset)+1)), (len(subset), m))
>>> indicator.A
array([[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 0, 0, 0, 0, 0]])
>>> 
# apply
>>> result = indicator@A
>>> result.A
array([[0, 0, 2, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 4, 0],
       [3, 0, 0, 0, 1, 4, 0, 0]], dtype=int64)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 scipy 稀疏矩阵的几行采样到另一个中 的相关文章

随机推荐