两个不同维数的稀疏矩阵的叠加

2024-09-22 16:22:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个稀疏矩阵(从sklearnHashVectorizer中创建,来自两组特性-每组对应于一个特性)。我想将它们连接起来,以便以后用于集群。但是,我面临一个维数的问题,因为这两个矩阵的行维数不同。在

下面是一个例子:

Xa = [-0.57735027 -0.57735027  0.57735027 -0.57735027 -0.57735027  0.57735027
  0.5         0.5        -0.5         0.5         0.5        -0.5         0.5
  0.5        -0.5         0.5        -0.5         0.5         0.5        -0.5
  0.5         0.5       ]

Xb = [-0.57735027 -0.57735027  0.57735027 -0.57735027  0.57735027  0.57735027
 -0.5         0.5         0.5         0.5        -0.5        -0.5         0.5
 -0.5        -0.5        -0.5         0.5         0.5       ]

Xa和{}都属于<class 'scipy.sparse.csr.csr_matrix'>类型。形状是Xa.shape = (6, 1048576) Xb.shape = (5, 1048576)。我得到的错误是(我现在知道为什么会发生):

^{pr2}$

尽管稀疏矩阵的维数不规则,但有没有一种方法可以将它们堆叠起来?也许加些衬垫?在

我看过这些帖子:


Tags: 集群矩阵scipy特性matrixclass例子sparse
1条回答
网友
1楼 · 发布于 2024-09-22 16:22:50

你可以用一个空的稀疏矩阵来填充它。在

你想要水平堆叠它,所以你需要填充较小的矩阵,这样它就拥有与大矩阵相同的行数。为此,将其垂直堆叠成(difference in number of rows, number of columns of original matrix)的矩阵。在

像这样:

from scipy.sparse import csr_matrix
from scipy.sparse import hstack
from scipy.sparse import vstack

# Create 2 empty sparse matrix for demo
Xa = csr_matrix((4, 4))
Xb = csr_matrix((3, 5))


diff_n_rows = Xa.shape[0] - Xb.shape[0]

Xb_new = vstack((Xb, csr_matrix((diff_n_rows, Xb.shape[1])))) 
#where diff_n_rows is the difference of the number of rows between Xa and Xb

X = hstack((Xa, Xb_new))
X

结果是:

^{pr2}$

相关问题 更多 >