【问题标题】:Which sparse matrix format is preferable for the construction of block matrices哪种稀疏矩阵格式更适合构建块矩阵
【发布时间】:2019-03-07 12:42:30
【问题描述】:

我想使用相应的scipy 格式之一构造一个块矩阵。最终,矩阵必须转换为 CSC。

我基本上将块作为(密集)numpy 数组(具有ndim == 2)或偶尔作为稀疏标识获得。对于每个行子集(从上到下),我从左到右添加相应的块。目前我正在创建矩阵,然后根据索引切片分配块。

我的问题(关于性能)如下:

  1. 建议使用切片还是我应该使用scipy.sparse.bmat 代替?
  2. 如果我使用切片,我应该使用哪种矩阵类型来插入块(我分配M[a:b,:]M[:,a:b] 形式的切片)?

【问题讨论】:

  • 只是猜测,但COO 感觉是处理块的自然选择。
  • 好吧,引用TypeError'coo_matrix' object does not support item assignment
  • coo 输入样式是原始的,并且仍然是构造稀疏矩阵的标准(如果不是在所有情况下都是最好的)。对于现有矩阵的迭代分配,lil 格式是最好的。 bmat 加入块的coo 属性,形成一个新的coo(然后转换为指定的格式)。这可能很方便,但不会更快。 bsr_matrix 是另一种选择,但我没有使用太多。

标签: python numpy scipy sparse-matrix


【解决方案1】:

我不知道 scipy 方法的效率如何,但是使用 coo 格式手动构建块矩阵相对简单。只需收集块的rowcoldata 属性,将块偏移添加到坐标(即rowcol),然后连接:

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]]

【讨论】:

    猜你喜欢
    • 2018-01-19
    • 1970-01-01
    • 2015-01-29
    • 2021-09-22
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 2013-11-29
    相关资源
    最近更新 更多