如何使用scipy稀疏矩阵对numpy数组进行column_stack? [英] How to column_stack a numpy array with a scipy sparse matrix?

查看:53
本文介绍了如何使用scipy稀疏矩阵对numpy数组进行column_stack?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下矩阵:

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,我尝试了以下方法:

I would like to column stack A and B in C, I tried the folowing:

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

我的问题是如何保留尺寸.因此,知道如何对它们进行列堆叠吗?.

My problem is how can I preserve the dimentions. Thus, any idea of how to column stack them?.

更新

我尝试了以下方法:

#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)

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

推荐答案

您是否尝试过以下操作?

Did you try the following?

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 是一个稀疏矩阵,并且您希望将输出保持为稀疏矩阵,您可以这样做:

If A is a sparse matrix, and you want to maintain the output as sparse, you could do:

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

这篇关于如何使用scipy稀疏矩阵对numpy数组进行column_stack?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆