【问题标题】:How to column_stack a numpy array with a scipy sparse matrix?如何使用 scipy 稀疏矩阵 column_stack 一个 numpy 数组?
【发布时间】:2016-11-24 16:42:13
【问题描述】:

我有以下矩阵:

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)

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

【问题讨论】:

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


【解决方案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))

【讨论】:

  • 我试过这个,但我得到:ValueError: all the input array dimensions except for the concatenation axis must match exactly
  • 另外A 是一个稀疏矩阵。
  • 在调用C = csr_matrix((C)) 之前,这不是C 的一个巨大的非稀疏版本吗?
  • @MadPhysicist 确实会。
【解决方案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 转换为稀疏矩阵。转置有效,因为它现在是一个矩阵(而不是一维数组):

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)

【讨论】:

    猜你喜欢
    • 2013-09-24
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 2012-11-24
    • 1970-01-01
    • 2023-04-05
    • 2016-08-26
    • 2012-12-20
    相关资源
    最近更新 更多