python - 如何将 coo_matrix 与列 numpy 数组连接

标签 python numpy scipy

我有一个 coo_matrix a ,形状为 (40106, 2048) 和一个列 numpy 数组 b ,其中形状(40106,)

我想要做的是简单地连接矩阵和数组(即生成的数据结构将具有形状 (40106, 2049) )。 我尝试使用 hstack ,如下所示

concat = hstack([a, b])

但我收到以下错误:

File "/Users/usr/anaconda/lib/python3.5/site-packages/scipy/sparse/construct.py", line 464, in hstack
    return bmat([blocks], format=format, dtype=dtype)
File "/Users/usr/anaconda/lib/python3.5/site-packages/scipy/sparse/construct.py", line 581, in bmat
    'row dimensions' % i)
ValueError: blocks[0,:] has incompatible row dimensions

我不太明白为什么尺寸不匹配,因为 ab 具有相同的行数。

最佳答案

我认为这是sparse.hstack。转换为矩阵后,您的 b 将为 (1,40106)。在将其传递给 hstack 之前,尝试将其转换为正确的稀疏矩阵。 hstack 将作业传递给 bmat,最终连接所有输入矩阵的 coo 属性,从而生成一个新矩阵

In [66]: from scipy import sparse
In [67]: A = sparse.coo_matrix(np.eye(3))
In [68]: b = np.ones(3)
In [69]: sparse.hstack((A,b))
....
ValueError: blocks[0,:] has incompatible row dimensions
In [70]: B=sparse.coo_matrix(b)
In [71]: B
Out[71]: 
<1x3 sparse matrix of type '<class 'numpy.float64'>'
    with 3 stored elements in COOrdinate format>
In [72]: sparse.hstack((A,B.T))
Out[72]: 
<3x4 sparse matrix of type '<class 'numpy.float64'>'
    with 6 stored elements in COOrdinate format>
In [73]: _.A
Out[73]: 
array([[ 1.,  0.,  0.,  1.],
       [ 0.,  1.,  0.,  1.],
       [ 0.,  0.,  1.,  1.]])

这也有效(如 Divakar 的回答):

In [74]: sparse.hstack((A,b[:,None]))
Out[74]: 
<3x4 sparse matrix of type '<class 'numpy.float64'>'
    with 6 stored elements in COOrdinate format>

我的 hastack 是这样的:

return bmat([blocks], format=format, dtype=dtype)

所以直接调用 bmat 也可以

In [93]: sparse.bmat([[A, B.T]])
Out[93]: 
<3x4 sparse matrix of type '<class 'numpy.float64'>'
    with 6 stored elements in COOrdinate format>

sparse.bmat([A, B.T]) 会产生 blocks Must be 2d 错误。

关于python - 如何将 coo_matrix 与列 numpy 数组连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43640862/

相关文章:

Python——在进程之间共享一个 Numpy 数组?

python - 如何控制 turtle 图形窗口的打开和关闭?

python - 如何在 Python 中执行局部多项式拟合

python - 将两个具有不同维度、标签的矩阵相加并在总和矩阵中保留标签

python - 检测矩阵中的对角线

javascript - 如何在 one2many odoo 13 上触发计算

python - Beautiful Soup 返回不完整的 HTML 脚本

python - 仅在正面积的 numpy 数组中集成

python - Matplotlib 和 Numpy 数学

python - 将两个数组聚合成具有给定形状的单个数组的正确方法