如何在Python中连接两个矩阵?

我有两个csr_matrix,uniFeature和biFeature。


我想要一个新的矩阵Feature = [uniFeature, biFeature]。但是,如果我以这种方式直接连接它们,则会出现一个错误,指出矩阵Feature是一个列表。如何实现矩阵级联并仍然获得相同类型的矩阵,即a 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_


白板的微信
浏览 310回答 1
1回答

holdtom

该scipy.sparse模块包括功能hstack和vstack。例如:In [44]: import scipy.sparse as spIn [45]: c1 = sp.csr_matrix([[0,0,1,0],&nbsp; &nbsp; ...:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[2,0,0,0],&nbsp; &nbsp; ...:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[0,0,0,0]])In [46]: c2 = sp.csr_matrix([[0,3,4,0],&nbsp; &nbsp; ...:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[0,0,0,5],&nbsp; &nbsp; ...:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[6,7,0,8]])In [47]: h = sp.hstack((c1, c2), format='csr')In [48]: hOut[48]:&nbsp;<3x8 sparse matrix of type '<type 'numpy.int64'>'&nbsp; &nbsp; with 8 stored elements in Compressed Sparse Row format>In [49]: h.AOut[49]:&nbsp;array([[0, 0, 1, 0, 0, 3, 4, 0],&nbsp; &nbsp; &nbsp; &nbsp;[2, 0, 0, 0, 0, 0, 0, 5],&nbsp; &nbsp; &nbsp; &nbsp;[0, 0, 0, 0, 6, 7, 0, 8]])In [50]: v = sp.vstack((c1, c2), format='csr')In [51]: vOut[51]:&nbsp;<6x4 sparse matrix of type '<type 'numpy.int64'>'&nbsp; &nbsp; with 8 stored elements in Compressed Sparse Row format>In [52]: v.AOut[52]:&nbsp;array([[0, 0, 1, 0],&nbsp; &nbsp; &nbsp; &nbsp;[2, 0, 0, 0],&nbsp; &nbsp; &nbsp; &nbsp;[0, 0, 0, 0],&nbsp; &nbsp; &nbsp; &nbsp;[0, 3, 4, 0],&nbsp; &nbsp; &nbsp; &nbsp;[0, 0, 0, 5],&nbsp; &nbsp; &nbsp; &nbsp;[6, 7, 0, 8]])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python