2014-10-20 22 views
6

我有一個MxN稀疏csr_matrix,我想在矩陣的右側添加只有零的幾列。原則上,陣列indptr,indicesdata保持不變,所以我只想改變矩陣的尺寸。但是,這似乎沒有實施。將一列零添加到csr_matrix中

>>> A = csr_matrix(np.identity(5), dtype = int) 
>>> A.toarray() 
array([[1, 0, 0, 0, 0], 
     [0, 1, 0, 0, 0], 
     [0, 0, 1, 0, 0], 
     [0, 0, 0, 1, 0], 
     [0, 0, 0, 0, 1]]) 
>>> A.shape 
(5, 5) 
>>> A.shape = ((5,7)) 
NotImplementedError: Reshaping not implemented for csr_matrix. 

也水平堆疊零矩陣似乎沒有工作。

>>> B = csr_matrix(np.zeros([5,2]), dtype = int) 
>>> B.toarray() 
array([[0, 0], 
     [0, 0], 
     [0, 0], 
     [0, 0], 
     [0, 0]]) 
>>> np.hstack((A,B)) 
array([ <5x5 sparse matrix of type '<type 'numpy.int32'>' 
    with 5 stored elements in Compressed Sparse Row format>, 
     <5x2 sparse matrix of type '<type 'numpy.int32'>' 
    with 0 stored elements in Compressed Sparse Row format>], dtype=object) 

這是我最終想達到的。有沒有一種快速的方法來重塑我的csr_matrix而不復制所有內容?

>>> C = csr_matrix(np.hstack((A.toarray(), B.toarray()))) 
>>> C.toarray() 
array([[1, 0, 0, 0, 0, 0, 0], 
     [0, 1, 0, 0, 0, 0, 0], 
     [0, 0, 1, 0, 0, 0, 0], 
     [0, 0, 0, 1, 0, 0, 0], 
     [0, 0, 0, 0, 1, 0, 0]]) 

回答

3

你想要做的不是真正的numpy或scipy理解爲重塑。但是,對於您的特定情況下,你可以創建一個新的CSR矩陣重用data,從原來的一個indicesindptr,無需將其複製:

import scipy.sparse as sps 

a = sps.rand(10000, 10000, density=0.01, format='csr') 

In [19]: %timeit sps.csr_matrix((a.data, a.indices, a.indptr), 
...        shape=(10000, 10020), copy=True) 
100 loops, best of 3: 6.26 ms per loop 

In [20]: %timeit sps.csr_matrix((a.data, a.indices, a.indptr), 
...        shape=(10000, 10020), copy=False) 
10000 loops, best of 3: 47.3 us per loop 

In [21]: %timeit sps.csr_matrix((a.data, a.indices, a.indptr), 
...        shape=(10000, 10020)) 
10000 loops, best of 3: 48.2 us per loop 

所以,如果你不再需要原來的矩陣a,因爲默認是copy=False,簡單地做:

a = sps.csr_matrix((a.data, a.indices, a.indptr), shape=(10000, 10020)) 
4

您可以使用scipy.sparse.vstackscipy.sparse.hstack做得更快:

from scipy.sparse import csr_matrix, vstack, hstack 

B = csr_matrix((5, 2), dtype=int) 
C = csr_matrix((5, 2), dtype=int) 
D = csr_matrix((10, 10), dtype=int) 

B2 = vstack((B, C)) 
#<10x2 sparse matrix of type '<type 'numpy.int32'>' 
#  with 0 stored elements in COOrdinate format> 

hstack((B2, D)) 
#<10x12 sparse matrix of type '<type 'numpy.int32'>' 
#  with 0 stored elements in COOrdinate format> 

注意,輸出的是coo_matrix,它可以有效地轉換爲CSRCSC格式。