使用int列表进行稀疏矩阵切片


问题内容

我正在针对庞大而稀疏的数据编写机器学习算法(我的矩阵的形状为(347,5 416 812 801),但非常稀疏,只有0.13%的数据为非零。

我的稀疏矩阵的大小为105 000字节(<1Mbytes),并且是csr类型。

我试图通过为每个选择示例索引列表来分离训练/测试集。所以我想使用以下方式将数据集一分为二:

training_set = matrix[train_indices]

形状(len(training_indices), 5 416 812 801)仍然稀疏

testing_set = matrix[test_indices]

形状(347-len(training_indices), 5 416 812 801)也稀疏

随着training_indicestesting_indices2listint

training_set = matrix[train_indices]似乎失败并返回一个Segmentation fault (core dumped)

这可能不是内存问题,因为我正在具有64 GB RAM的服务器上运行此代码。

关于可能的原因有什么线索?


问题答案:

我想我csr用以下方法重新创建了行索引:

def extractor(indices, N):
   indptr=np.arange(len(indices)+1)
   data=np.ones(len(indices))
   shape=(len(indices),N)
   return sparse.csr_matrix((data,indices,indptr), shape=shape)

csr我在周围徘徊的测试:

In [185]: M
Out[185]: 
<30x40 sparse matrix of type '<class 'numpy.float64'>'
    with 76 stored elements in Compressed Sparse Row format>

In [186]: indices=np.r_[0:20]

In [187]: M[indices,:]
Out[187]: 
<20x40 sparse matrix of type '<class 'numpy.float64'>'
    with 57 stored elements in Compressed Sparse Row format>

In [188]: extractor(indices, M.shape[0])*M
Out[188]: 
<20x40 sparse matrix of type '<class 'numpy.float64'>'
    with 57 stored elements in Compressed Sparse Row format>

与许多其他csr方法一样,它使用矩阵乘法来产生最终值。在这种情况下,所选行中的稀疏矩阵为1。时间实际上好一点。

In [189]: timeit M[indices,:]
1000 loops, best of 3: 515 µs per loop
In [190]: timeit extractor(indices, M.shape[0])*M
1000 loops, best of 3: 399 µs per loop

在您的情况下,提取器矩阵的形状为(len(train_indices),347),只有len(training_indices)值。所以不大。

但是,如果amatrix太大(或至少第二维那么大),从而在矩阵乘法例程中产生一些错误,则可能会导致分段错误而没有python / numpy捕获它。

确实matrix.sum(axis=1)有效。尽管使用了1s的密集矩阵,但它也使用了矩阵乘法。或者sparse.eye(347)*M,类似的大小矩阵乘法?