使用 SciPy/Numpy 在 Python 中连接稀疏矩阵 [英] Concatenate sparse matrices in Python using SciPy/Numpy

查看:43
本文介绍了使用 SciPy/Numpy 在 Python 中连接稀疏矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中使用 SciPy/Numpy 连接稀疏矩阵的最有效方法是什么?

这里我使用了以下内容:

<预><代码>>>>np.hstack((X, X2))数组([ <49998x70000 稀疏矩阵类型 '<class 'numpy.float64'>'以压缩稀疏行格式存储 1135520 个元素>,<49998x70000 '<class 'numpy.int64'>' 类型的稀疏矩阵以压缩稀疏行格式存储 1135520 个元素>],数据类型=对象)

我想在回归中同时使用这两个预测变量,但当前的格式显然不是我想要的.是否有可能获得以下内容:

 <49998x1400000 ' 类型的稀疏矩阵以压缩稀疏行格式存储 2271040 个元素>

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

解决方案

您可以使用 scipy.sparse.hstack 来连接具有相同行数的稀疏矩阵(水平连接):

from scipy.sparse import hstackhstack((X, X2))

同样,您可以使用 scipy.sparse.vstack 连接具有相同列数的稀疏矩阵(垂直连接).

使用 numpy.hstacknumpy.vstack 将创建一个包含两个稀疏矩阵对象的数组.

What would be the most efficient way to concatenate sparse matrices in Python using SciPy/Numpy?

Here I used the following:

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

I would like to use both predictors in a regression, but the current format is obviously not what I'm looking for. Would it be possible to get the following:

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

It is too large to be converted to a deep format.

解决方案

You can use the scipy.sparse.hstack to concatenate sparse matrices with the same number of rows (horizontal concatenation):

from scipy.sparse import hstack
hstack((X, X2))

Similarly, you can use scipy.sparse.vstack to concatenate sparse matrices with the same number of columns (vertical concatenation).

Using numpy.hstack or numpy.vstack will create an array with two sparse matrix objects.

这篇关于使用 SciPy/Numpy 在 Python 中连接稀疏矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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