joh*_*doe 7 python numpy machine-learning scipy scikit-learn
我有 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>
Run Code Online (Sandbox Code Playgroud)
从文档中,我了解到可以使用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
Run Code Online (Sandbox Code Playgroud)
但是,尺寸不匹配:
In [41]:
X_combined_features.shape
Out[41]:
(2, 1)
Run Code Online (Sandbox Code Playgroud)
请注意,我正在堆叠这些矩阵,因为我想将它们与 scikit-learn 分类算法一起使用。因此,我应该如何处理hstack多个不同的稀疏矩阵?.
使用sparse的版本vstack。作为一般规则,您需要使用稀疏函数和方法,而不是numpy名称相似的函数和方法。 sparse矩阵不是 的子类numpy ndarray。
但是,您的 3 个三个矩阵看起来并不稀疏。它们是 1x878049。一个有 878048 个非零元素 - 这意味着只有一个 0 元素。
因此,您也可以将它们转换为密集数组(使用.toarray()或.A)并使用np.hstack或np.vstack。
np.hstack([address_feature.A, dayweek_feature.A])
Run Code Online (Sandbox Code Playgroud)
并且不要使用双括号。所有连接函数都采用一个简单的数组列表或元组。并且该列表可以有 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)
Run Code Online (Sandbox Code Playgroud)