堆叠稀疏和密集的矩阵

Abh*_*kur 6 python arrays numpy matrix scipy

是否可以在python中堆叠稀疏和密集的numpy数组?我知道这可以使用vstack/hstack为密集的numpy数组完成.我有一些列,我想添加到稀疏矩阵,以增加特征向量的数量

Sau*_*tro 10

是的,您可以使用scipy.sparse.vstackscipy.sparse.hstack使用numpy.vstacknumpy.hstack使用密集阵列相同的方式.

例:

from scipy.sparse import coo_matrix
m = coo_matrix(np.array([[0,0,1],[1,0,0],[1,0,0]]))
a = np.ones(m.shape)
Run Code Online (Sandbox Code Playgroud)

np.vstack:

np.vstack((a,m))
#ValueError: all the input array dimensions except for the concatenation axis must match exactly
Run Code Online (Sandbox Code Playgroud)

scipy.sparse.vstack:

scipy.sparse.vstack((a,m))
#<6x3 sparse matrix of type '<type 'numpy.float64'>'
#        with 12 stored elements in COOrdinate format>
Run Code Online (Sandbox Code Playgroud)