Python 将scipy稀疏矩阵的几行采样到另一行
如何对scipy稀疏矩阵的某些行进行采样,并从这些采样行形成新的scipy稀疏矩阵Python 将scipy稀疏矩阵的几行采样到另一行,python,python-3.x,numpy,scipy,Python,Python 3.x,Numpy,Scipy,如何对scipy稀疏矩阵的某些行进行采样,并从这些采样行形成新的scipy稀疏矩阵 例如,如果我有一个包含10行的scipy稀疏矩阵a,并且我想从a中生成一个包含第1、3、4行的新scipy稀疏矩阵B,该如何做?左乘以适当的指示符矩阵。可以使用scipy.sparse.block_diag或直接使用csr格式构建指标矩阵,如下所示 >>> import numpy as np >>> from scipy import sparse >>>
例如,如果我有一个包含10行的scipy稀疏矩阵a,并且我想从a中生成一个包含第1、3、4行的新scipy稀疏矩阵B,该如何做?左乘以适当的指示符矩阵。可以使用
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)
有没有办法索引行,然后将它们附加到新矩阵中?我实际上想做的是创建一个新的矩阵,比如说原始矩阵的第1行k次,原始矩阵的第3行l次,原始矩阵的第4行m次。看起来使用vstack是一种方法。但是它的效率非常低,因为它创建了一个新的矩阵来垂直堆叠每一行。@Sujay_K你是说缩放还是重复?在第一种情况下,使用
indicator=sparse.csr\u矩阵((您的权重,子集,np.arange(len(子集)+1)),(len(子集),m))
。在第二种情况下,使用`indicator=sparse.csr_矩阵((np.one(np.sum(your_repeats),int),np.repeat(subset,your_repeats),np.arange(np.sum(your_repeats)+1)),(np.sum(your_repeats),m))@hpaulj很好知道。谢谢@Sujay_K,警告主要是为了阻止它在循环中反复使用。对于一次性操作,索引的csr
设置可能仍然比备选设置快(例如转换为lil
)。