【问题标题】:How to hstack several sparse matrices (feature matrices)?如何hstack几个稀疏矩阵(特征矩阵)?
【发布时间】:2016-10-09 13:26:13
【问题描述】:

我有 3 个稀疏矩阵:

In [39]:

mat1


Out[39]:
(1, 878049)
<1x878049 sparse matrix of type '<type 'numpy.int64'>'
    with 878048 stored elements in Compressed Sparse Row format>

In [37]:

mat2


Out[37]:
(1, 878049)
<1x878049 sparse matrix of type '<type 'numpy.int64'>'
    with 744315 stored elements in Compressed Sparse Row format>

In [35]:

mat3



Out[35]:
(1, 878049)
<1x878049 sparse matrix of type '<type 'numpy.int64'>'
    with 788618 stored elements in Compressed Sparse Row format>

从documentation 中,我了解到hstack、vstack 和concatenate 可以使用此类矩阵。于是我尝试hstack他们:

import numpy as np

matrix1 = np.hstack([[address_feature, dayweek_feature]]).T
matrix2 = np.vstack([[matrix1, pddis_feature]]).T


X = matrix2

但是,尺寸不匹配:

In [41]:

X_combined_features.shape

Out[41]:

(2, 1)

请注意,我正在堆叠此类矩阵,因为我想将它们与 scikit-learn 分类算法一起使用。因此,我应该如何hstack多个不同的稀疏矩阵?。

【问题讨论】:

    标签: python numpy machine-learning scipy scikit-learn


    【解决方案1】:

    使用sparse 版本的vstack。作为一般规则,您需要使用稀疏函数和方法,而不是具有相似名称的numpy。 sparse 矩阵不是 numpy ndarray 的子类。

    但是,您的 3 个三个矩阵看起来并不稀疏。它们是 1x878049。一个有 878048 个非零元素 - 这意味着只有一个 0 元素。

    因此,您也可以将它们变成密集数组(使用.toarray() 或.A)并使用np.hstack 或np.vstack。

    np.hstack([address_feature.A, dayweek_feature.A])
    

    并且不要使用双括号。所有连接函数都采用数组的简单列表或元组。并且该列表可以有超过 2 个数组

    In [296]: A=sparse.csr_matrix([0,1,2,0,0,1])
    
    In [297]: B=sparse.csr_matrix([0,0,0,1,0,1])
    
    In [298]: C=sparse.csr_matrix([1,0,0,0,1,0])
    
    In [299]: sparse.vstack([A,B,C])
    Out[299]: 
    <3x6 sparse matrix of type '<class 'numpy.int32'>'
        with 7 stored elements in Compressed Sparse Row format>
    
    In [300]: sparse.vstack([A,B,C]).A
    Out[300]: 
    array([[0, 1, 2, 0, 0, 1],
           [0, 0, 0, 1, 0, 1],
           [1, 0, 0, 0, 1, 0]], dtype=int32)
    
    In [301]: sparse.hstack([A,B,C]).A
    Out[301]: array([[0, 1, 2, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0]], dtype=int32)
    
    In [302]: np.vstack([A.A,B.A,C.A])
    Out[302]: 
    array([[0, 1, 2, 0, 0, 1],
           [0, 0, 0, 1, 0, 1],
           [1, 0, 0, 0, 1, 0]], dtype=int32)
    

    【讨论】:

    • 感谢您的帮助,很好的回答!
    猜你喜欢
    • 2013-09-25
    • 1970-01-01
    • 2023-03-29
    • 2021-09-22
    • 1970-01-01
    • 2019-12-16
    • 2018-01-19
    • 1970-01-01
    • 2015-08-24
    相关资源
    最近更新 更多