SciPy でのスパース行列のサイズ変更に関する別の投稿では、受け入れられた回答は、それぞれscipy.sparse.vstack
またはを使用して行または列を追加する場合に機能hstack
します。SciPy 0.12 では、reshape
orset_shape
メソッドはまだ実装されていません。
SciPy 0.12 でスパース行列を再形成するための安定したグッド プラクティスはありますか? タイミングの比較ができると良いです。
SciPy でのスパース行列のサイズ変更に関する別の投稿では、受け入れられた回答は、それぞれscipy.sparse.vstack
またはを使用して行または列を追加する場合に機能hstack
します。SciPy 0.12 では、reshape
orset_shape
メソッドはまだ実装されていません。
SciPy 0.12 でスパース行列を再形成するための安定したグッド プラクティスはありますか? タイミングの比較ができると良いです。
確立された優れたプラクティスについては知らないので、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]])
さて、私はここに何人かの定期的な貢献者がいると確信しています.
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
完全な開示: 私は実装を書きました。