Skip to main content
 首页 » 编程设计

python之如何将 coo_matrix 与列 numpy 数组连接起来

2024年10月01日10over140

我有一个形状为 (40106, 2048) 的 coo_matrix a 和一个列 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 

我不太明白为什么维度不匹配,因为 a 和 b 具有相同的行数。

请您参考如下方法:

我假设那是 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 错误。