如何在Python中连接两个矩阵? [英] How to concatenate two matrices in Python?

查看:85
本文介绍了如何在Python中连接两个矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 csr_matrix uniFeature biFeature .

我想要一个新的矩阵 Feature = [uniFeature,biFeature] .但是,如果我以这种方式直接连接它们,则会出现一个错误,指出矩阵 Feature 是一个列表.我如何才能实现矩阵级联并仍然获得相同类型的矩阵,即 csr_matrix ?

I want a new matrix Feature = [uniFeature, biFeature]. But if I directly concatenate them this way, there's an error that says the matrix Feature is a list. How can I achieve the matrix concatenation and still get the same type of matrix, i.e. a csr_matrix?

如果我在连接后执行此操作,将不起作用: Feature = csr_matrix(Feature)它给出了错误:

And it doesn't work if I do this after the concatenation: Feature = csr_matrix(Feature) It gives the error:

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_

推荐答案

scipy.sparse 模块包含功能 hstack vstack .

例如:

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]])

这篇关于如何在Python中连接两个矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆