2013-06-02 3 views
6

나는 두 개의 csr_matrix, uniFeaturebiFeature을 가지고 있습니다.파이썬에서 두 개의 행렬을 연결하는 방법은 무엇입니까?

새 매트릭스가 필요합니다. 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()에 예상치 못한 키워드 인수 'format'이 있습니다 – Moh

+0

해결 : 문제 : scipy.parse 모듈을 가져 오는 대신 scipy를 가져 왔습니다. – Moh

관련 문제