使用SciPy/Numpy在Python中连接稀疏矩阵

49

如何在Python中使用SciPy/Numpy最有效地连接稀疏矩阵?

这里我使用了以下方法:

>>> np.hstack((X, X2))
array([ <49998x70000 sparse matrix of type '<class 'numpy.float64'>'
        with 1135520 stored elements in Compressed Sparse Row format>,
        <49998x70000 sparse matrix of type '<class 'numpy.int64'>'
        with 1135520 stored elements in Compressed Sparse Row format>], 
       dtype=object)

我希望在回归中使用这两个预测变量,但目前的格式显然不符合我的要求。请问是否可以得到以下格式:

    <49998x1400000 sparse matrix of type '<class 'numpy.float64'>'
     with 2271040 stored elements in Compressed Sparse Row format>

它太大了,无法转换为深度格式。

1个回答

85
你可以使用scipy.sparse.hstack将具有相同行数的稀疏矩阵连接在一起(水平连接):
from scipy.sparse import hstack
hstack((X, X2))

同样地,你可以使用 scipy.sparse.vstack 来将具有相同列数的稀疏矩阵连接起来(纵向连接)。

使用 numpy.hstacknumpy.vstack 会创建一个由两个稀疏矩阵对象组成的数组。


2
似乎hstack非常慢,可以查看类似问题的这篇帖子链接 - simeon
1
@simeon 有趣的是,Scipy的开发团队没有采用这样高效的解决方案。 - Saullo G. P. Castro
1
可以使用水平拼接函数hstack()和垂直拼接函数vstack()。 - mgokhanbakal

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