如何使用scipy稀疏矩阵column_stack一个numpy数组?

时间:2016-07-21 07:57:39

标签: python python-2.7 python-3.x numpy scipy

我有以下矩阵:

A.toarray()

array([[0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       ..., 
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]], dtype=int64)

type(A)

scipy.sparse.csr.csr_matrix

A.shape
(878049, 942)

矩阵B:

B

array([2248, 2248, 2248, ...,    0,    0,    0])

type(B)

numpy.ndarray

B.shape

(878049,)

我想在C中填充AB列,我尝试了下面的内容:

C =  sparse.column_stack([A,B])

然后:

/usr/local/lib/python3.5/site-packages/numpy/lib/shape_base.py in column_stack(tup)
    315             arr = array(arr, copy=False, subok=True, ndmin=2).T
    316         arrays.append(arr)
--> 317     return _nx.concatenate(arrays, 1)
    318 
    319 def dstack(tup):

ValueError: all the input array dimensions except for the concatenation axis must match exactly

我的问题是如何保留尺寸。那么,任何关于如何列堆叠它们的想法?。

更新

我尝试了以下内容:

#Sorry for the name
C =  np.vstack(( A.A.T, B)).T

我得到了:

array([[   0,    0,    0, ...,    0,    6],
       [   0,    0,    0, ...,    0,    6],
       [   0,    0,    0, ...,    0,    6],
       ..., 
       [   0,    0,    0, ...,    0,    1],
       [   0,    0,    0, ...,    0,    1],
       [   0,    0,    0, ...,    0,    1]], dtype=int64)

这是列堆叠它们的正确方法吗?

2 个答案:

答案 0 :(得分:2)

2个问题

  • 没有sparse.column_stack
  • 你正在混合一个稀疏矩阵和密集阵列

2个较小的例子:

In [129]: A=sparse.csr_matrix([[1,0,0],[0,1,0]])
In [130]: B=np.array([1,2])

使用np.column_stack会出错:

In [131]: np.column_stack((A,B))
... 
ValueError: all the input array dimensions except for the concatenation axis must match exactly

但如果我先将A转换为数组,则column_stack可以正常运行:

In [132]: np.column_stack((A.A, B))
Out[132]: 
array([[1, 0, 0, 1],
       [0, 1, 0, 2]])

等同于concatenate

In [133]: np.concatenate((A.A, B[:,None]), axis=1)
Out[133]: 
array([[1, 0, 0, 1],
       [0, 1, 0, 2]])

有一个sparse.hstack。为此,我还需要将B转换为稀疏矩阵。转置是有效的,因为它现在是一个矩阵(而不是1d数组):

In [134]: sparse.hstack((A,sparse.csr_matrix(B).T))
Out[134]: 
<2x4 sparse matrix of type '<class 'numpy.int32'>'
    with 4 stored elements in COOrdinate format>
In [135]: _.A
Out[135]: 
array([[1, 0, 0, 1],
       [0, 1, 0, 2]], dtype=int32)

答案 1 :(得分:1)

您是否尝试过以下操作?

C=np.vstack((A.T,B)).T

使用样本值:

A = array([[1, 2, 3], [4, 5, 6]])
>>>> A.shape
(2, 3)
B = array([7, 8])
>>> B.shape
(2,)
C=np.vstack((A.T,B)).T
>>> C.shape
(2, 4)

如果A是稀疏矩阵,并且您希望将输出保持为稀疏,则可以这样做:

C=np.vstack((A.A.T,B)).T
D=csr_matrix((C))