4

SciPy でのスパース行列のサイズ変更に関する別の投稿では、受け入れられた回答は、それぞれscipy.sparse.vstackまたはを使用して行または列を追加する場合に機能hstackします。SciPy 0.12 では、reshapeorset_shapeメソッドはまだ実装されていません。

SciPy 0.12 でスパース行列を再形成するための安定したグッド プラクティスはありますか? タイミングの比較ができると良いです。

4

3 に答える 3

8

確立された優れたプラクティスについては知らないので、coo_matrix のかなり単純な reshape 関数を次に示します。引数を coo_matrix に変換するため、他のスパース形式でも実際に機能します (ただし、coo_matrix を返します)。

from scipy.sparse import coo_matrix


def reshape(a, shape):
    """Reshape the sparse matrix `a`.

    Returns a coo_matrix with shape `shape`.
    """
    if not hasattr(shape, '__len__') or len(shape) != 2:
        raise ValueError('`shape` must be a sequence of two integers')

    c = a.tocoo()
    nrows, ncols = c.shape
    size = nrows * ncols

    new_size =  shape[0] * shape[1]
    if new_size != size:
        raise ValueError('total size of new array must be unchanged')

    flat_indices = ncols * c.row + c.col
    new_row, new_col = divmod(flat_indices, shape[1])

    b = coo_matrix((c.data, (new_row, new_col)), shape=shape)
    return b

例:

In [43]: a = coo_matrix([[0,10,0,0],[0,0,0,0],[0,20,30,40]])

In [44]: a.A
Out[44]: 
array([[ 0, 10,  0,  0],
       [ 0,  0,  0,  0],
       [ 0, 20, 30, 40]])

In [45]: b = reshape(a, (2,6))

In [46]: b.A
Out[46]: 
array([[ 0, 10,  0,  0,  0,  0],
       [ 0,  0,  0, 20, 30, 40]])

さて、私はここに何人かの定期的な貢献者がいると確信しています.

于 2013-05-13T23:02:28.070 に答える
2

SciPy 1.1.0の時点で、すべての疎行列タイプに対して メソッドreshapeとメソッドが実装されています。set_shape署名は期待どおりのものであり、可能な限り NumPy の同等のメソッドと同じです (たとえば、ベクトルまたはテンソルに再形成することはできません)。

サイン:

reshape(self, shape: Tuple[int, int], order: 'C'|'F' = 'C', copy: bool = False) -> spmatrix

例:

>>> from scipy.sparse import csr_matrix
>>> A = csr_matrix([[0,0,2,0], [0,1,0,3]])
>>> print(A)
  (0, 2)    2
  (1, 1)    1
  (1, 3)    3
>>> B = A.reshape((4,2))
>>> print(B)
  (1, 0)    2
  (2, 1)    1
  (3, 1)    3
>>> C = A.reshape((4,2), order='F')
>>> print(C)
  (0, 1)    2
  (3, 0)    1
  (3, 1)    3

完全な開示: 私は実装を書きました。

于 2019-02-04T13:37:36.590 に答える