【问题标题】:how can I combine multiple sparse and dense matrices together如何将多个稀疏和密集矩阵组合在一起
【发布时间】:2019-07-16 07:11:31
【问题描述】:

我一直在处理一些文本数据,但我得到的稀疏矩阵和密集矩阵(numpy 数组)很少。我只是想知道如何正确组合它们。

这些是数组的类型和形状:

list1 
<109248x9 sparse matrix of type '<class 'numpy.int64'>'
    with 152643 stored elements in Compressed Sparse Row format>

list2
<109248x3141 sparse matrix of type '<class 'numpy.int64'>'
    with 350145 stored elements in Compressed Sparse Row format>

list3.shape   ,  type(list3)
(109248, 300) ,  numpy.ndarray

list4.shape   ,  type
(109248, 51)  ,  numpy.ndarray

我只想将所有这些组合成一个密集矩阵。我尝试了一些 vstack 和 hstack 但无法弄清楚。非常感谢任何帮助。

Output required: (109248, 3501)

【问题讨论】:

  • 把稀疏的变成稠密的,例如list1.A,然后`hstack全部4个的列表
  • @hpaulj 我尝试使用list2.toarray(),但出现错误。 memory error。是否可以直接组合它而不实际将它们转换为密集的?
  • 使密集数组稀疏,并使用sparse.hstack
  • 参见stackoverflow.com/questions/16505670/… 了解如何将稀疏矩阵变为密集矩阵

标签: python python-3.x numpy scipy sparse-matrix


【解决方案1】:

sparse.hstack 可以加入稀疏和密集数组。它首先将所有内容转换为coo 格式矩阵,创建一个新的复合datarowcol 数组,并返回一个coo 矩阵(可选择将其转换为另一种指定格式):

In [379]: M=sparse.random(10,10,.2,'csr')                                       
In [380]: M                                                                     
Out[380]: 
<10x10 sparse matrix of type '<class 'numpy.float64'>'
    with 20 stored elements in Compressed Sparse Row format>
In [381]: A=np.ones((10,2),float)                                               
In [382]: sparse.hstack([M,A])                                                  
Out[382]: 
<10x12 sparse matrix of type '<class 'numpy.float64'>'
    with 40 stored elements in COOrdinate format>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-27
    • 1970-01-01
    • 2016-06-25
    • 2019-05-06
    • 2021-12-18
    • 2019-09-02
    • 1970-01-01
    • 2013-03-07
    相关资源
    最近更新 更多