2017-04-26 145 views
2

我有coo_matrixa形状(40106, 2048)和列numpy阵列b形状(40106,)如何连接coo_matrix与列numpy阵列

我想要做的是简单地连接矩阵和数组(即结果数据结构将具有形状(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有相同的行数。

+1

我认为这是'sparse.hstack'。当转换为矩阵时,你的'b'将是(1,40106)。在将它传递给'hstack'之前,尝试将它转换为正确的稀疏矩阵。 'hstack'将作业传递给'bmat',最后加入所有输入矩阵的'coo'属性,从而创建一个新的矩阵。 – hpaulj

回答

1

我认为这是sparse.hstack。转换为矩阵时,您的b将为(1,40106)。尝试将它转换为正确的稀疏矩阵,然后传递给hstackhstack传递作业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错误。

+0

两种方法我得到一个'ValueError:块必须是2-D'错误。 –

+0

如果我使用'sparse.hstack([[A,B.T]])'',我会得到那个错误。 'sparse.bmat([[A,B.T]])'也适用。我使用0.18.1 scipy。 'hstack'如何将其输入转换为'bmat's'可能存在版本错误。 – hpaulj

+0

我也使用0.18.1 scipy。现在''sparse.bmat([[A,BT]])给出了TypeError:不支持类型转换:(dtype('float64'),dtype('

1

转换的第二阵列,这是1D2D和使用,然后hstack -

hstack([A,B[:,None]]) 

采样运行 -

In [86]: from scipy.sparse import coo_matrix, hstack 

# Sample inputs as a coo_matrix and an array 
In [87]: A = coo_matrix([[1, 2, 0], [3, 0, 4]]) 
    ...: B = np.array([5, 6]) 
    ...: 

# Use proposed solution 
In [88]: out = hstack([A,B[:,None]]) 

# Print the dense version to visually verify 
In [89]: out.toarray() 
Out[89]: 
array([[1, 2, 0, 5], 
     [3, 0, 4, 6]]) 
+0

现在numpy数组的形状是'(40106,1)',但我得到以下错误:'ValueError:块必须是2-D' –

+0

@ Old-school您是否在使用'from'from scipy.sparse导入hstack'? – Divakar

+0

是的,我正在使用'从'scipy.sparse导入hstack''hstack' –