如何将多个稀疏矩阵和密集矩阵组合在一起?

6

我一直在处理一些文本数据,有一些稀疏矩阵和密集(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,然后将所有4个列表进行 hstack - hpaulj
@hpaulj 我尝试使用list2.toarray(),但出现了错误。内存错误。是否可以直接合并它们,而无需实际转换为密集数组? - user_6396
将密集数组变为稀疏数组,并使用sparse.hstack - hpaulj
请参见 https://dev59.com/DGQn5IYBdhLWcg3w36XV#16505766 了解如何将稀疏矩阵转换为密集矩阵。 - Rachel Gallen
1个回答

6

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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接