2013-06-02 41 views
6

我有兩個csr_matrix,uniFeaturebiFeature如何連接Python中的兩個矩陣?

我想要一個新的矩陣Feature = [uniFeature, biFeature]。但是,如果我以這種方式直接連接它們,那麼表示矩陣Feature是一個列表。我怎樣才能實現矩陣連接,並仍然得到相同類型的矩陣,即csr_matrix

而且如果我這樣做了連接後它不工作:Feature = csr_matrix(Feature) 它給人的錯誤:

Traceback (most recent call last): 
    File "yelpfilter.py", line 91, in <module> 
    Feature = csr_matrix(Feature) 
    File "c:\python27\lib\site-packages\scipy\sparse\compressed.py", line 66, in __init__ 
    self._set_self(self.__class__(coo_matrix(arg1, dtype=dtype))) 
    File "c:\python27\lib\site-packages\scipy\sparse\coo.py", line 185, in __init__ 
    self.row, self.col = M.nonzero() 
TypeError: __nonzero__ should return bool or int, returned numpy.bool_ 

回答

15

scipy.sparse模塊包括的功能hstackvstack

例如:

In [44]: import scipy.sparse as sp 

In [45]: c1 = sp.csr_matrix([[0,0,1,0], 
    ...:      [2,0,0,0], 
    ...:      [0,0,0,0]]) 

In [46]: c2 = sp.csr_matrix([[0,3,4,0], 
    ...:      [0,0,0,5], 
    ...:      [6,7,0,8]]) 

In [47]: h = sp.hstack((c1, c2), format='csr') 

In [48]: h 
Out[48]: 
<3x8 sparse matrix of type '<type 'numpy.int64'>' 
    with 8 stored elements in Compressed Sparse Row format> 

In [49]: h.A 
Out[49]: 
array([[0, 0, 1, 0, 0, 3, 4, 0], 
     [2, 0, 0, 0, 0, 0, 0, 5], 
     [0, 0, 0, 0, 6, 7, 0, 8]]) 

In [50]: v = sp.vstack((c1, c2), format='csr') 

In [51]: v 
Out[51]: 
<6x4 sparse matrix of type '<type 'numpy.int64'>' 
    with 8 stored elements in Compressed Sparse Row format> 

In [52]: v.A 
Out[52]: 
array([[0, 0, 1, 0], 
     [2, 0, 0, 0], 
     [0, 0, 0, 0], 
     [0, 3, 4, 0], 
     [0, 0, 0, 5], 
     [6, 7, 0, 8]]) 
+0

非常感謝!正是我需要的 –

+0

我得到這個錯誤: TypeError:vstack()得到了一個意想不到的關鍵字參數「格式」 – Moh

+0

已解決:問題是: 而不是導入scipy.parse模塊,我已經導入scipy – Moh