我想使用相应的scipy格式之一构造一个块矩阵。最终,矩阵必须转换为CSC。
我实际上获得的块是(密集的)numpy数组(具有ndim == 2
)或偶尔是稀疏的标识。对于行的每个子集(从上到下),我从左到右添加相应的块。目前,我正在创建矩阵,然后根据索引切片分配块。
我的问题(关于表现)如下:
scipy.sparse.bmat
?M[a:b,:]
和M[:,a:b]
的形式分配切片)?答案 0 :(得分:1)
我不知道scipy方法的效率如何,但是使用coo
格式,手工构建块矩阵相对简单。所有需要做的就是收集块的row
,col
和data
属性,将块偏移量添加到坐标(即row
和col
),然后串联:
import numpy as np
from scipy import sparse
from collections import namedtuple
from operator import attrgetter
submat = namedtuple('submat', 'row_offset col_offset block')
def join_blocks(blocks):
roff, coff, mat = zip(*blocks)
row, col, data = zip(*map(attrgetter('row', 'col', 'data'), mat))
row = [o + r for o, r in zip(roff, row)]
col = [o + c for o, c in zip(coff, col)]
row, col, data = map(np.concatenate, (row, col, data))
return sparse.coo_matrix((data, (row, col))).tocsr()
example = [*map(submat, range(0, 10, 2), range(8, -2, -2), map(sparse.coo_matrix, np.multiply.outer([6, 2, 1, 3, 4], [[1, 0], [-1, 1]])))]
print('Example:')
for sm in example:
print(sm)
print('\nCombined')
print(join_blocks(example).A)
打印:
Example:
submat(row_offset=0, col_offset=8, block=<2x2 sparse matrix of type '<class 'numpy.int64'>'
with 3 stored elements in COOrdinate format>)
submat(row_offset=2, col_offset=6, block=<2x2 sparse matrix of type '<class 'numpy.int64'>'
with 3 stored elements in COOrdinate format>)
submat(row_offset=4, col_offset=4, block=<2x2 sparse matrix of type '<class 'numpy.int64'>'
with 3 stored elements in COOrdinate format>)
submat(row_offset=6, col_offset=2, block=<2x2 sparse matrix of type '<class 'numpy.int64'>'
with 3 stored elements in COOrdinate format>)
submat(row_offset=8, col_offset=0, block=<2x2 sparse matrix of type '<class 'numpy.int64'>'
with 3 stored elements in COOrdinate format>)
Combined
[[ 0 0 0 0 0 0 0 0 6 0]
[ 0 0 0 0 0 0 0 0 -6 6]
[ 0 0 0 0 0 0 2 0 0 0]
[ 0 0 0 0 0 0 -2 2 0 0]
[ 0 0 0 0 1 0 0 0 0 0]
[ 0 0 0 0 -1 1 0 0 0 0]
[ 0 0 3 0 0 0 0 0 0 0]
[ 0 0 -3 3 0 0 0 0 0 0]
[ 4 0 0 0 0 0 0 0 0 0]
[-4 4 0 0 0 0 0 0 0 0]]